]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
* Painter.h:
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "buffer.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
28 #include "factory.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
32 #include "gettext.h"
33 #include "intl.h"
34 #include "insetiterator.h"
35 #include "language.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
38 #include "lyx_main.h"
39 #include "lyxfind.h"
40 #include "lyxfunc.h"
41 #include "lyxlayout.h"
42 #include "lyxtext.h"
43 #include "lyxtextclass.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "texrow.h"
51 #include "toc.h"
52 #include "undo.h"
53 #include "vspace.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
61
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
65
66 #include "graphics/Previews.h"
67
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
73
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
76
77 #include <functional>
78 #include <vector>
79
80
81 namespace lyx {
82
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
91
92 using std::distance;
93 using std::endl;
94 using std::istringstream;
95 using std::make_pair;
96 using std::min;
97 using std::max;
98 using std::mem_fun_ref;
99 using std::string;
100 using std::vector;
101
102 namespace Alert = frontend::Alert;
103
104 namespace {
105
106 unsigned int const saved_positions_num = 20;
107
108
109 /// Return an inset of this class if it exists at the current cursor position
110 template <class T>
111 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
112 {
113         T * inset = 0;
114         DocIterator it = cur;
115         if (it.nextInset() &&
116             it.nextInset()->lyxCode() == code) {
117                 inset = static_cast<T*>(it.nextInset());
118         }
119         return inset;
120 }
121
122 } // anon namespace
123
124
125 BufferView::BufferView()
126         : width_(0), height_(0), buffer_(0), wh_(0),
127           cursor_(*this),
128           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
129           intl_(new Intl)
130 {
131         xsel_cache_.set = false;
132
133         saved_positions.resize(saved_positions_num);
134         // load saved bookmarks
135         BookmarksSection::BookmarkList & bmList = LyX::ref().session().bookmarks().load();
136         for (BookmarksSection::BookmarkList::iterator bm = bmList.begin();
137                 bm != bmList.end(); ++bm)
138                 if (bm->get<0>() < saved_positions_num)
139                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
140         // and then clear them
141         bmList.clear();
142
143         intl_->initKeyMapper(lyxrc.use_kbmap);
144 }
145
146
147 BufferView::~BufferView()
148 {
149 }
150
151
152 Buffer * BufferView::buffer() const
153 {
154         return buffer_;
155 }
156
157
158 void BufferView::setBuffer(Buffer * b)
159 {
160         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
161                             << "[ b = " << b << "]" << endl;
162
163         if (buffer_) {
164                 // Save the actual cursor position and anchor inside the
165                 // buffer so that it can be restored in case we rechange
166                 // to this buffer later on.
167                 buffer_->saveCursor(cursor_.selectionBegin(),
168                                     cursor_.selectionEnd());
169                 // current buffer is going to be switched-off, save cursor pos
170                 LyX::ref().session().lastFilePos().save(buffer_->fileName(),
171                         boost::tie(cursor_.pit(), cursor_.pos()) );
172         }
173
174         // If we're quitting lyx, don't bother updating stuff
175         if (quitting) {
176                 buffer_ = 0;
177                 return;
178         }
179
180         // If we are closing current buffer, switch to the first in
181         // buffer list.
182         if (!b) {
183                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
184                                     << " No Buffer!" << endl;
185                 // We are closing the buffer, use the first buffer as current
186                 buffer_ = theBufferList().first();
187         } else {
188                 // Set current buffer
189                 buffer_ = b;
190         }
191
192         // Reset old cursor
193         cursor_ = LCursor(*this);
194         anchor_ref_ = 0;
195         offset_ref_ = 0;
196
197         if (buffer_) {
198                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
199                                     << "Buffer addr: " << buffer_ << endl;
200                 cursor_.push(buffer_->inset());
201                 cursor_.resetAnchor();
202                 buffer_->text().init(this);
203                 buffer_->text().setCurrentFont(cursor_);
204                 if (buffer_->getCursor().size() > 0 &&
205                     buffer_->getAnchor().size() > 0)
206                 {
207                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
208                         cursor_.resetAnchor();
209                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
210                         cursor_.setSelection();
211                 }
212         }
213
214         update();
215
216         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
217                 graphics::Previews::get().generateBufferPreviews(*buffer_);
218 }
219
220
221 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
222 {
223         // Get absolute path of file and add ".lyx"
224         // to the filename if necessary
225         string s = fileSearch(string(), filename, "lyx");
226
227         bool const found = !s.empty();
228
229         if (!found)
230                 s = filename;
231
232         // File already open?
233         if (theBufferList().exists(s)) {
234                 docstring const file = makeDisplayPath(s, 20);
235                 docstring text = bformat(_("The document %1$s is already "
236                                                      "loaded.\n\nDo you want to revert "
237                                                      "to the saved version?"), file);
238                 int const ret = Alert::prompt(_("Revert to saved document?"),
239                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
240
241                 if (ret != 0) {
242                         setBuffer(theBufferList().getBuffer(s));
243                         return true;
244                 }
245                 // FIXME: should be LFUN_REVERT
246                 if (!theBufferList().close(theBufferList().getBuffer(s), false))
247                         return false;
248                 // Fall through to new load. (Asger)
249                 buffer_ = 0;
250         }
251
252         Buffer * b = 0;
253
254         if (found) {
255                 b = theBufferList().newBuffer(s);
256                 if (!lyx::loadLyXFile(b, s)) {
257                         theBufferList().release(b);
258                         return false;
259                 }
260         } else {
261                 docstring text = bformat(_("The document %1$s does not yet "
262                                                      "exist.\n\nDo you want to create "
263                                                      "a new document?"), from_utf8(s));
264                 int const ret = Alert::prompt(_("Create new document?"),
265                          text, 0, 1, _("&Create"), _("Cancel"));
266
267                 if (ret == 0) {
268                         b = newFile(s, string(), true);
269                         if (!b)
270                                 return false;
271                 } else
272                         return false;
273         }
274
275         setBuffer(b);
276         // Send the "errors" signal in case of parsing errors
277         b->errors("Parse");
278
279         // scroll to the position when the file was last closed
280         if (lyxrc.use_lastfilepos) {
281                 pit_type pit;
282                 pos_type pos;
283                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
284                 // I am not sure how to separate the following part to a function
285                 // so I will leave this to Lars.
286                 //
287                 // check pit since the document may be externally changed.
288                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
289                         ParIterator it = b->par_iterator_begin();
290                         ParIterator const end = b->par_iterator_end();
291                         for (; it != end; ++it)
292                                 if (it.pit() == pit) {
293                                         // restored pos may be bigger than it->size
294                                         setCursor(makeDocIterator(it, min(pos, it->size())));
295                                         update(Update::FitCursor);
296                                         break;
297                                 }
298                 }
299         }
300
301         if (tolastfiles)
302                 LyX::ref().session().lastFiles().add(b->fileName());
303
304         return true;
305 }
306
307
308 void BufferView::reload()
309 {
310         string const fn = buffer_->fileName();
311         if (theBufferList().close(buffer_, false))
312                 loadLyXFile(fn);
313 }
314
315
316 void BufferView::resize()
317 {
318         if (!buffer_)
319                 return;
320
321         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
322
323         buffer_->text().init(this);
324         update();
325         switchKeyMap();
326 }
327
328
329 bool BufferView::fitCursor()
330 {
331         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
332                 frontend::FontMetrics const & fm =
333                         theFontMetrics(cursor_.getFont());
334                 int const asc = fm.maxAscent();
335                 int const des = fm.maxDescent();
336                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
337                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
338                         return false;
339         }
340         center();
341         return true;
342 }
343
344
345 bool BufferView::multiParSel()
346 {
347         if (!cursor_.selection())
348                 return false;
349         bool ret = multiparsel_cache_;
350         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
351         // Either this, or previous selection spans paragraphs
352         return ret || multiparsel_cache_;
353 }
354
355
356 bool BufferView::update(Update::flags flags)
357 {
358         // This is close to a hot-path.
359         if (lyxerr.debugging(Debug::DEBUG)) {
360                 lyxerr[Debug::DEBUG]
361                         << BOOST_CURRENT_FUNCTION
362                         << "[fitcursor = " << (flags & Update::FitCursor)
363                         << ", forceupdate = " << (flags & Update::Force)
364                         << ", singlepar = " << (flags & Update::SinglePar)
365                         << "]  buffer: " << buffer_ << endl;
366         }
367
368         // Check needed to survive LyX startup
369         if (!buffer_)
370                 return false;
371
372         lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
373
374         // Update macro store
375         buffer_->buildMacros();
376
377         // First drawing step
378         updateMetrics(flags & Update::SinglePar);
379
380         // The second drawing step is done in WorkArea::redraw() if needed.
381         bool const need_second_step =
382                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
383                 && (fitCursor() || multiParSel());
384
385         return need_second_step;
386 }
387
388
389 void BufferView::updateScrollbar()
390 {
391         if (!buffer_) {
392                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
393                                      << " no text in updateScrollbar" << endl;
394                 scrollbarParameters_.reset();
395                 return;
396         }
397
398         LyXText & t = buffer_->text();
399         int const parsize = int(t.paragraphs().size() - 1);
400         if (anchor_ref_ >  parsize)  {
401                 anchor_ref_ = parsize;
402                 offset_ref_ = 0;
403         }
404
405         lyxerr[Debug::GUI]
406                 << BOOST_CURRENT_FUNCTION
407                 << " Updating scrollbar: height: " << t.paragraphs().size()
408                 << " curr par: " << cursor_.bottom().pit()
409                 << " default height " << defaultRowHeight() << endl;
410
411         // It would be better to fix the scrollbar to understand
412         // values in [0..1] and divide everything by wh
413
414         // estimated average paragraph height:
415         if (wh_ == 0)
416                 wh_ = height_ / 4;
417         int h = t.getPar(anchor_ref_).height();
418
419         // Normalize anchor/offset (MV):
420         while (offset_ref_ > h && anchor_ref_ < parsize) {
421                 anchor_ref_++;
422                 offset_ref_ -= h;
423                 h = t.getPar(anchor_ref_).height();
424         }
425         // Look at paragraph heights on-screen
426         int sumh = 0;
427         int nh = 0;
428         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
429                 if (sumh > height_)
430                         break;
431                 int const h2 = t.getPar(pit).height();
432                 sumh += h2;
433                 nh++;
434         }
435
436         BOOST_ASSERT(nh);
437         int const hav = sumh / nh;
438         // More realistic average paragraph height
439         if (hav > wh_)
440                 wh_ = hav;
441
442         BOOST_ASSERT(h);
443         scrollbarParameters_.height = (parsize + 1) * wh_;
444         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
445         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
446 }
447
448
449 ScrollbarParameters const & BufferView::scrollbarParameters() const
450 {
451         return scrollbarParameters_;
452 }
453
454
455 void BufferView::scrollDocView(int value)
456 {
457         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
458                            << "[ value = " << value << "]" << endl;
459
460         if (!buffer_)
461                 return;
462
463         LyXText & t = buffer_->text();
464
465         float const bar = value / float(wh_ * t.paragraphs().size());
466
467         anchor_ref_ = int(bar * t.paragraphs().size());
468         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
469                 anchor_ref_ = int(t.paragraphs().size()) - 1;
470         t.redoParagraph(anchor_ref_);
471         int const h = t.getPar(anchor_ref_).height();
472         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
473 }
474
475
476 void BufferView::setCursorFromScrollbar()
477 {
478         LyXText & t = buffer_->text();
479
480         int const height = 2 * defaultRowHeight();
481         int const first = height;
482         int const last = height_ - height;
483         LCursor & cur = cursor_;
484
485         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
486
487         switch (st) {
488         case bv_funcs::CUR_ABOVE:
489                 t.setCursorFromCoordinates(cur, 0, first);
490                 cur.clearSelection();
491                 break;
492         case bv_funcs::CUR_BELOW:
493                 t.setCursorFromCoordinates(cur, 0, last);
494                 cur.clearSelection();
495                 break;
496         case bv_funcs::CUR_INSIDE:
497                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
498                 int const newy = min(last, max(y, first));
499                 if (y != newy) {
500                         cur.reset(buffer_->inset());
501                         t.setCursorFromCoordinates(cur, 0, newy);
502                 }
503         }
504 }
505
506
507 Change const BufferView::getCurrentChange() const
508 {
509         if (!cursor_.selection())
510                 return Change(Change::UNCHANGED);
511
512         DocIterator dit = cursor_.selectionBegin();
513         return dit.paragraph().lookupChange(dit.pos());
514 }
515
516
517 void BufferView::savePosition(unsigned int i)
518 {
519         if (i >= saved_positions_num)
520                 return;
521         BOOST_ASSERT(cursor_.inTexted());
522         saved_positions[i] = Position(buffer_->fileName(),
523                                       cursor_.paragraph().id(),
524                                       cursor_.pos());
525         if (i > 0)
526                 // emit message signal.
527                 message(bformat(_("Saved bookmark %1$d"), i));
528 }
529
530
531 void BufferView::restorePosition(unsigned int i)
532 {
533         if (i >= saved_positions_num)
534                 return;
535
536         string const fname = saved_positions[i].filename;
537
538         cursor_.clearSelection();
539
540         if (fname != buffer_->fileName()) {
541                 Buffer * b = 0;
542                 if (theBufferList().exists(fname))
543                         b = theBufferList().getBuffer(fname);
544                 else {
545                         b = theBufferList().newBuffer(fname);
546                         // Don't ask, just load it
547                         lyx::loadLyXFile(b, fname);
548                 }
549                 if (b)
550                         setBuffer(b);
551         }
552
553         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
554         if (par == buffer_->par_iterator_end())
555                 return;
556
557         setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
558
559         if (i > 0)
560                 // emit message signal.
561                 message(bformat(_("Moved to bookmark %1$d"), i));
562 }
563
564
565 bool BufferView::isSavedPosition(unsigned int i)
566 {
567         return i < saved_positions_num && !saved_positions[i].filename.empty();
568 }
569
570 void BufferView::saveSavedPositions()
571 {
572         // save bookmarks. It is better to use the pit interface
573         // but I do not know how to effectively convert between
574         // par_id and pit.
575         for (unsigned int i=1; i < saved_positions_num; ++i) {
576                 if ( isSavedPosition(i) )
577                         LyX::ref().session().bookmarks().save( boost::tie(
578                                 i,
579                                 saved_positions[i].filename,
580                                 saved_positions[i].par_id,
581                                 saved_positions[i].par_pos) );
582         }
583 }
584
585 void BufferView::switchKeyMap()
586 {
587         if (!lyxrc.rtl_support)
588                 return;
589
590         if (getLyXText()->real_current_font.isRightToLeft()) {
591                 if (intl_->keymap == Intl::PRIMARY)
592                         intl_->keyMapSec();
593         } else {
594                 if (intl_->keymap == Intl::SECONDARY)
595                         intl_->keyMapPrim();
596         }
597 }
598
599
600 int BufferView::workWidth() const
601 {
602         return width_;
603 }
604
605
606 void BufferView::center()
607 {
608         CursorSlice & bot = cursor_.bottom();
609         pit_type const pit = bot.pit();
610         bot.text()->redoParagraph(pit);
611         Paragraph const & par = bot.text()->paragraphs()[pit];
612         anchor_ref_ = pit;
613         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
614                 + par.ascent() - height_ / 2;
615 }
616
617
618 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
619 {
620         FuncStatus flag;
621
622         switch (cmd.action) {
623
624         case LFUN_UNDO:
625                 flag.enabled(!buffer_->undostack().empty());
626                 break;
627         case LFUN_REDO:
628                 flag.enabled(!buffer_->redostack().empty());
629                 break;
630         case LFUN_FILE_INSERT:
631         case LFUN_FILE_INSERT_ASCII_PARA:
632         case LFUN_FILE_INSERT_ASCII:
633         case LFUN_BOOKMARK_SAVE:
634                 // FIXME: Actually, these LFUNS should be moved to LyXText
635                 flag.enabled(cursor_.inTexted());
636                 break;
637         case LFUN_FONT_STATE:
638         case LFUN_LABEL_INSERT:
639         case LFUN_PARAGRAPH_GOTO:
640         // FIXME handle non-trivially
641         case LFUN_OUTLINE_UP:
642         case LFUN_OUTLINE_DOWN:
643         case LFUN_OUTLINE_IN:
644         case LFUN_OUTLINE_OUT:
645         case LFUN_NOTE_NEXT:
646         case LFUN_REFERENCE_NEXT:
647         case LFUN_WORD_FIND:
648         case LFUN_WORD_REPLACE:
649         case LFUN_MARK_OFF:
650         case LFUN_MARK_ON:
651         case LFUN_MARK_TOGGLE:
652         case LFUN_SCREEN_RECENTER:
653         case LFUN_BIBTEX_DATABASE_ADD:
654         case LFUN_BIBTEX_DATABASE_DEL:
655         case LFUN_WORDS_COUNT:
656         case LFUN_NEXT_INSET_TOGGLE:
657                 flag.enabled(true);
658                 break;
659
660         case LFUN_LABEL_GOTO: {
661                 flag.enabled(!cmd.argument().empty()
662                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
663                 break;
664         }
665
666         case LFUN_BOOKMARK_GOTO:
667                 flag.enabled(isSavedPosition(convert<unsigned int>(to_utf8(cmd.argument()))));
668                 break;
669
670         case LFUN_CHANGES_TRACK:
671                 flag.enabled(true);
672                 flag.setOnOff(buffer_->params().trackChanges);
673                 break;
674
675         case LFUN_CHANGES_OUTPUT: {
676                 OutputParams runparams;
677                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
678                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
679                 flag.setOnOff(buffer_->params().outputChanges);
680                 break;
681         }
682
683         case LFUN_CHANGES_MERGE:
684         case LFUN_CHANGE_NEXT:
685         case LFUN_ALL_CHANGES_ACCEPT:
686         case LFUN_ALL_CHANGES_REJECT:
687                 flag.enabled(buffer_); // FIXME: Change tracking (MG)
688                 break;
689
690         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
691                 flag.setOnOff(buffer_->params().compressed);
692                 break;
693         }
694
695         default:
696                 flag.enabled(false);
697         }
698
699         return flag;
700 }
701
702
703 bool BufferView::dispatch(FuncRequest const & cmd)
704 {
705         //lyxerr << BOOST_CURRENT_FUNCTION
706         //       << [ cmd = " << cmd << "]" << endl;
707
708         // Make sure that the cached BufferView is correct.
709         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
710                 << " action[" << cmd.action << ']'
711                 << " arg[" << to_utf8(cmd.argument()) << ']'
712                 << " x[" << cmd.x << ']'
713                 << " y[" << cmd.y << ']'
714                 << " button[" << cmd.button() << ']'
715                 << endl;
716
717         LCursor & cur = cursor_;
718
719         switch (cmd.action) {
720
721         case LFUN_UNDO:
722                 if (buffer_) {
723                         cur.message(_("Undo"));
724                         cur.clearSelection();
725                         if (!textUndo(*this))
726                                 cur.message(_("No further undo information"));
727                         update();
728                         switchKeyMap();
729                 }
730                 break;
731
732         case LFUN_REDO:
733                 if (buffer_) {
734                         cur.message(_("Redo"));
735                         cur.clearSelection();
736                         if (!textRedo(*this))
737                                 cur.message(_("No further redo information"));
738                         update();
739                         switchKeyMap();
740                 }
741                 break;
742
743         case LFUN_FILE_INSERT:
744                 // FIXME: We don't know the encoding of filenames
745                 menuInsertLyXFile(to_utf8(cmd.argument()));
746                 break;
747
748         case LFUN_FILE_INSERT_ASCII_PARA:
749                 // FIXME: We don't know the encoding of filenames
750                 insertAsciiFile(this, to_utf8(cmd.argument()), true);
751                 break;
752
753         case LFUN_FILE_INSERT_ASCII:
754                 // FIXME: We don't know the encoding of filenames
755                 insertAsciiFile(this, to_utf8(cmd.argument()), false);
756                 break;
757
758         case LFUN_FONT_STATE:
759                 cur.message(from_utf8(cur.currentState()));
760                 break;
761
762         case LFUN_BOOKMARK_SAVE:
763                 savePosition(convert<unsigned int>(to_utf8(cmd.argument())));
764                 break;
765
766         case LFUN_BOOKMARK_GOTO:
767                 restorePosition(convert<unsigned int>(to_utf8(cmd.argument())));
768                 break;
769
770         case LFUN_LABEL_GOTO: {
771                 docstring label = cmd.argument();
772                 if (label.empty()) {
773                         InsetRef * inset =
774                                 getInsetByCode<InsetRef>(cursor_,
775                                                          InsetBase::REF_CODE);
776                         if (inset) {
777                                 label = inset->getParam("reference");
778                                 savePosition(0);
779                         }
780                 }
781
782                 if (!label.empty())
783                         gotoLabel(label);
784                 break;
785         }
786
787         case LFUN_PARAGRAPH_GOTO: {
788                 int const id = convert<int>(to_utf8(cmd.argument()));
789                 ParIterator par = buffer_->getParFromID(id);
790                 if (par == buffer_->par_iterator_end()) {
791                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
792                                             << id << ']' << endl;
793                         break;
794                 } else {
795                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
796                                             << " found." << endl;
797                 }
798
799                 // Set the cursor
800                 setCursor(makeDocIterator(par, 0));
801
802                 update();
803                 switchKeyMap();
804                 break;
805         }
806
807         case LFUN_OUTLINE_UP:
808                 toc::outline(toc::Up, cursor_);
809                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
810                 updateLabels(*buffer_);
811                 break;
812         case LFUN_OUTLINE_DOWN:
813                 toc::outline(toc::Down, cursor_);
814                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
815                 updateLabels(*buffer_);
816                 break;
817         case LFUN_OUTLINE_IN:
818                 toc::outline(toc::In, cursor_);
819                 updateLabels(*buffer_);
820                 break;
821         case LFUN_OUTLINE_OUT:
822                 toc::outline(toc::Out, cursor_);
823                 updateLabels(*buffer_);
824                 break;
825
826         case LFUN_NOTE_NEXT:
827                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
828                 break;
829
830         case LFUN_REFERENCE_NEXT: {
831                 vector<InsetBase_code> tmp;
832                 tmp.push_back(InsetBase::LABEL_CODE);
833                 tmp.push_back(InsetBase::REF_CODE);
834                 bv_funcs::gotoInset(this, tmp, true);
835                 break;
836         }
837
838         case LFUN_CHANGES_TRACK:
839                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
840                 break;
841
842         case LFUN_CHANGES_OUTPUT: {
843                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
844                 break;
845         }
846
847         case LFUN_CHANGE_NEXT:
848                 findNextChange(this);
849                 break;
850
851         case LFUN_CHANGES_MERGE:
852                 if (findNextChange(this))
853                         showDialog("changes");
854                 break;
855
856         case LFUN_ALL_CHANGES_ACCEPT: {
857                 cursor_.reset(buffer_->inset());
858 #ifdef WITH_WARNINGS
859 #warning FIXME changes
860 #endif
861                 while (findNextChange(this))
862                         getLyXText()->acceptChange(cursor_);
863                 update();
864                 break;
865         }
866
867         case LFUN_ALL_CHANGES_REJECT: {
868                 cursor_.reset(buffer_->inset());
869 #ifdef WITH_WARNINGS
870 #warning FIXME changes
871 #endif
872                 while (findNextChange(this))
873                         getLyXText()->rejectChange(cursor_);
874                 break;
875         }
876
877         case LFUN_WORD_FIND:
878                 find(this, cmd);
879                 break;
880
881         case LFUN_WORD_REPLACE:
882                 replace(this, cmd);
883                 break;
884
885         case LFUN_MARK_OFF:
886                 cur.clearSelection();
887                 cur.resetAnchor();
888                 cur.message(from_utf8(N_("Mark off")));
889                 break;
890
891         case LFUN_MARK_ON:
892                 cur.clearSelection();
893                 cur.mark() = true;
894                 cur.resetAnchor();
895                 cur.message(from_utf8(N_("Mark on")));
896                 break;
897
898         case LFUN_MARK_TOGGLE:
899                 cur.clearSelection();
900                 if (cur.mark()) {
901                         cur.mark() = false;
902                         cur.message(from_utf8(N_("Mark removed")));
903                 } else {
904                         cur.mark() = true;
905                         cur.message(from_utf8(N_("Mark set")));
906                 }
907                 cur.resetAnchor();
908                 break;
909
910         case LFUN_SCREEN_RECENTER:
911                 center();
912                 break;
913
914         case LFUN_BIBTEX_DATABASE_ADD: {
915                 LCursor tmpcur = cursor_;
916                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
917                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
918                                                 InsetBase::BIBTEX_CODE);
919                 if (inset) {
920                         if (inset->addDatabase(to_utf8(cmd.argument())))
921                                 buffer_->updateBibfilesCache();
922                 }
923                 break;
924         }
925
926         case LFUN_BIBTEX_DATABASE_DEL: {
927                 LCursor tmpcur = cursor_;
928                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
929                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
930                                                 InsetBase::BIBTEX_CODE);
931                 if (inset) {
932                         if (inset->delDatabase(to_utf8(cmd.argument())))
933                                 buffer_->updateBibfilesCache();
934                 }
935                 break;
936         }
937
938         case LFUN_WORDS_COUNT: {
939                 DocIterator from, to;
940                 if (cur.selection()) {
941                         from = cur.selectionBegin();
942                         to = cur.selectionEnd();
943                 } else {
944                         from = doc_iterator_begin(buffer_->inset());
945                         to = doc_iterator_end(buffer_->inset());
946                 }
947                 int const count = countWords(from, to);
948                 docstring message;
949                 if (count != 1) {
950                         if (cur.selection())
951                                 message = bformat(_("%1$d words in selection."),
952                                           count);
953                                 else
954                                         message = bformat(_("%1$d words in document."),
955                                                           count);
956                 }
957                 else {
958                         if (cur.selection())
959                                 message = _("One word in selection.");
960                         else
961                                 message = _("One word in document.");
962                 }
963
964                 Alert::information(_("Count words"), message);
965         }
966                 break;
967
968         case LFUN_BUFFER_TOGGLE_COMPRESSION:
969                 // turn compression on/off
970                 buffer_->params().compressed = !buffer_->params().compressed;
971                 break;
972
973         case LFUN_NEXT_INSET_TOGGLE: {
974                 // this is the real function we want to invoke
975                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
976                 // if there is an inset at cursor, see whether it
977                 // wants to toggle.
978                 InsetBase * inset = cur.nextInset();
979                 if (inset && inset->isActive()) {
980                         LCursor tmpcur = cur;
981                         tmpcur.pushLeft(*inset);
982                         inset->dispatch(tmpcur, tmpcmd);
983                         if (tmpcur.result().dispatched()) {
984                                 cur.dispatched();
985                         }
986                 }
987                 // if it did not work, try the underlying inset.
988                 if (!cur.result().dispatched())
989                         cur.dispatch(tmpcmd);
990
991                 if (cur.result().dispatched())
992                         cur.clearSelection();
993
994                 break;
995         }
996
997         default:
998                 return false;
999         }
1000
1001         return true;
1002 }
1003
1004
1005 docstring const BufferView::requestSelection()
1006 {
1007         if (!buffer_)
1008                 return docstring();
1009
1010         LCursor & cur = cursor_;
1011
1012         if (!cur.selection()) {
1013                 xsel_cache_.set = false;
1014                 return docstring();
1015         }
1016
1017         if (!xsel_cache_.set ||
1018             cur.top() != xsel_cache_.cursor ||
1019             cur.anchor_.top() != xsel_cache_.anchor)
1020         {
1021                 xsel_cache_.cursor = cur.top();
1022                 xsel_cache_.anchor = cur.anchor_.top();
1023                 xsel_cache_.set = cur.selection();
1024                 return cur.selectionAsString(false);
1025         }
1026         return docstring();
1027 }
1028
1029
1030 void BufferView::clearSelection()
1031 {
1032         if (buffer_) {
1033                 cursor_.clearSelection();
1034                 xsel_cache_.set = false;
1035         }
1036 }
1037
1038
1039 void BufferView::workAreaResize(int width, int height)
1040 {
1041         bool const widthChange = width != width_;
1042         bool const heightChange = height != height_;
1043
1044         // Update from work area
1045         width_ = width;
1046         height_ = height;
1047
1048         if (buffer_ && widthChange) {
1049                 // The WorkArea content needs a resize
1050                 resize();
1051         }
1052
1053         if (widthChange || heightChange)
1054                 update();
1055 }
1056
1057
1058 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1059 {
1060         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1061
1062         // This is only called for mouse related events including
1063         // LFUN_FILE_OPEN generated by drag-and-drop.
1064         FuncRequest cmd = cmd0;
1065
1066         if (!buffer_)
1067                 return false;
1068
1069         LCursor cur(*this);
1070         cur.push(buffer_->inset());
1071         cur.selection() = cursor_.selection();
1072
1073         // Doesn't go through lyxfunc, so we need to update
1074         // the layout choice etc. ourselves
1075
1076         // E.g. Qt mouse press when no buffer
1077         if (!buffer_)
1078                 return false;
1079
1080         // Either the inset under the cursor or the
1081         // surrounding LyXText will handle this event.
1082
1083         // Build temporary cursor.
1084         cmd.y = min(max(cmd.y, -1), height_);
1085         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1086         //lyxerr << BOOST_CURRENT_FUNCTION
1087         //       << " * hit inset at tip: " << inset << endl;
1088         //lyxerr << BOOST_CURRENT_FUNCTION
1089         //       << " * created temp cursor:" << cur << endl;
1090
1091         // Put anchor at the same position.
1092         cur.resetAnchor();
1093
1094         // Try to dispatch to an non-editable inset near this position
1095         // via the temp cursor. If the inset wishes to change the real
1096         // cursor it has to do so explicitly by using
1097         //  cur.bv().cursor() = cur;  (or similar)
1098         if (inset)
1099                 inset->dispatch(cur, cmd);
1100
1101         // Now dispatch to the temporary cursor. If the real cursor should
1102         // be modified, the inset's dispatch has to do so explicitly.
1103         if (!cur.result().dispatched())
1104                 cur.dispatch(cmd);
1105
1106         if (cur.result().dispatched()) {
1107                 // Redraw if requested or necessary.
1108                 if (cur.result().update())
1109                         update(Update::FitCursor | Update::Force);
1110                 else
1111                         update(Update::FitCursor | Update::MultiParSel);
1112         }
1113
1114         return true;
1115 }
1116
1117
1118 void BufferView::scroll(int /*lines*/)
1119 {
1120 //      if (!buffer_)
1121 //              return;
1122 //
1123 //      LyXText const * t = &buffer_->text();
1124 //      int const line_height = defaultRowHeight();
1125 //
1126 //      // The new absolute coordinate
1127 //      int new_top_y = top_y() + lines * line_height;
1128 //
1129 //      // Restrict to a valid value
1130 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1131 //      new_top_y = std::max(0, new_top_y);
1132 //
1133 //      scrollDocView(new_top_y);
1134 //
1135 //      // Update the scrollbar.
1136 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1137 }
1138
1139
1140 void BufferView::setCursorFromRow(int row)
1141 {
1142         int tmpid = -1;
1143         int tmppos = -1;
1144
1145         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1146
1147         if (tmpid == -1)
1148                 buffer_->text().setCursor(cursor_, 0, 0);
1149         else
1150                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1151 }
1152
1153
1154 void BufferView::gotoLabel(docstring const & label)
1155 {
1156         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1157                 vector<docstring> labels;
1158                 it->getLabelList(*buffer_, labels);
1159                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1160                         setCursor(it);
1161                         update();
1162                         return;
1163                 }
1164         }
1165 }
1166
1167
1168 LyXText * BufferView::getLyXText()
1169 {
1170         LyXText * text = cursor_.innerText();
1171         BOOST_ASSERT(text);
1172         return text;
1173 }
1174
1175
1176 LyXText const * BufferView::getLyXText() const
1177 {
1178         LyXText const * text = cursor_.innerText();
1179         BOOST_ASSERT(text);
1180         return text;
1181 }
1182
1183
1184 int BufferView::workHeight() const
1185 {
1186         return height_;
1187 }
1188
1189
1190 void BufferView::setCursor(DocIterator const & dit)
1191 {
1192         size_t const n = dit.depth();
1193         for (size_t i = 0; i < n; ++i)
1194                 dit[i].inset().edit(cursor_, true);
1195
1196         cursor_.setCursor(dit);
1197         cursor_.selection() = false;
1198 }
1199
1200
1201 void BufferView::mouseSetCursor(LCursor & cur)
1202 {
1203         BOOST_ASSERT(&cur.bv() == this);
1204
1205         // Has the cursor just left the inset?
1206         bool badcursor = false;
1207         if (&cursor_.inset() != &cur.inset())
1208                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1209
1210         // do the dEPM magic if needed
1211         // FIXME: move this to InsetText::notifyCursorLeaves?
1212         if (!badcursor && cursor_.inTexted())
1213                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1214
1215         cursor_ = cur;
1216         cursor_.clearSelection();
1217         cursor_.setTargetX();
1218         finishUndo();
1219
1220 }
1221
1222
1223 void BufferView::putSelectionAt(DocIterator const & cur,
1224                                 int length, bool backwards)
1225 {
1226         cursor_.clearSelection();
1227
1228         setCursor(cur);
1229
1230         if (length) {
1231                 if (backwards) {
1232                         cursor_.pos() += length;
1233                         cursor_.setSelection(cursor_, -length);
1234                 } else
1235                         cursor_.setSelection(cursor_, length);
1236         }
1237 }
1238
1239
1240 LCursor & BufferView::cursor()
1241 {
1242         return cursor_;
1243 }
1244
1245
1246 LCursor const & BufferView::cursor() const
1247 {
1248         return cursor_;
1249 }
1250
1251
1252 pit_type BufferView::anchor_ref() const
1253 {
1254         return anchor_ref_;
1255 }
1256
1257
1258 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1259 {
1260         return metrics_info_;
1261 }
1262
1263
1264 void BufferView::updateMetrics(bool singlepar)
1265 {
1266         // FIXME (Abdel 19/10/2006):
1267         // There's something fishy in tabular. The coord_cache_ is not
1268         // correctly reconstructed when a character is trying to be inserted.
1269         // Not clearing out the coord_cache_ fixes the crash but there is a
1270         // bad side effect: buffer-begin and buffer-end do not update the screen.
1271         //
1272         // Remove old position cache
1273         coord_cache_.clear();
1274
1275         LyXText & buftext = buffer_->text();
1276         pit_type size = int(buftext.paragraphs().size());
1277
1278         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1279                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1280                 offset_ref_ = 0;
1281         }
1282
1283         pit_type const pit = anchor_ref_;
1284         int pit1 = pit;
1285         int pit2 = pit;
1286         size_t const npit = buftext.paragraphs().size();
1287
1288         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1289         // the (main text, not inset!) paragraph containing the cursor.
1290         // (if this paragraph contains insets etc., rebreaking will
1291         // recursively descend)
1292         if (!singlepar || pit == cursor_.bottom().pit())
1293                 buftext.redoParagraph(pit);
1294         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1295
1296         // Redo paragraphs above anchor if necessary; again, in Single Par
1297         // mode, only if we encounter the (main text) one having the cursor.
1298         int y1 = y0;
1299         while (y1 > 0 && pit1 > 0) {
1300                 y1 -= buftext.getPar(pit1).ascent();
1301                 --pit1;
1302                 if (!singlepar || pit1 == cursor_.bottom().pit())
1303                         buftext.redoParagraph(pit1);
1304                 y1 -= buftext.getPar(pit1).descent();
1305         }
1306
1307
1308         // Take care of ascent of first line
1309         y1 -= buftext.getPar(pit1).ascent();
1310
1311         // Normalize anchor for next time
1312         anchor_ref_ = pit1;
1313         offset_ref_ = -y1;
1314
1315         // Grey at the beginning is ugly
1316         if (pit1 == 0 && y1 > 0) {
1317                 y0 -= y1;
1318                 y1 = 0;
1319                 anchor_ref_ = 0;
1320         }
1321
1322         // Redo paragraphs below the anchor if necessary. Single par mode:
1323         // only the one containing the cursor if encountered.
1324         int y2 = y0;
1325         while (y2 < height_ && pit2 < int(npit) - 1) {
1326                 y2 += buftext.getPar(pit2).descent();
1327                 ++pit2;
1328                 if (!singlepar || pit2 == cursor_.bottom().pit())
1329                         buftext.redoParagraph(pit2);
1330                 y2 += buftext.getPar(pit2).ascent();
1331         }
1332
1333         // Take care of descent of last line
1334         y2 += buftext.getPar(pit2).descent();
1335
1336         // The coordinates of all these paragraphs are correct, cache them
1337         int y = y1;
1338         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1339         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1340                 Paragraph const & par = buftext.getPar(pit);
1341                 y += par.ascent();
1342                 parPos[pit] = Point(0, y);
1343                 if (singlepar && pit == cursor_.bottom().pit()) {
1344                         // In Single Paragraph mode, collect here the
1345                         // y1 and y2 of the (one) paragraph the cursor is in
1346                         y1 = y - par.ascent();
1347                         y2 = y + par.descent();
1348                 }
1349                 y += par.descent();
1350         }
1351
1352         if (singlepar) {
1353                 // collect cursor paragraph iter bounds
1354                 pit1 = cursor_.bottom().pit();
1355                 pit2 = cursor_.bottom().pit();
1356         }
1357
1358         lyxerr[Debug::DEBUG]
1359                 << BOOST_CURRENT_FUNCTION
1360                 << " y1: " << y1
1361                 << " y2: " << y2
1362                 << " pit1: " << pit1
1363                 << " pit2: " << pit2
1364                 << " npit: " << npit
1365                 << " singlepar: " << singlepar
1366                 << "size: " << size
1367                 << endl;
1368
1369         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1370
1371         if (lyxerr.debugging(Debug::WORKAREA)) {
1372                 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1373                 coord_cache_.dump();
1374         }
1375 }
1376
1377
1378 void BufferView::menuInsertLyXFile(string const & filenm)
1379 {
1380         BOOST_ASSERT(cursor_.inTexted());
1381         string filename = filenm;
1382
1383         if (filename.empty()) {
1384                 // Launch a file browser
1385                 // FIXME UNICODE
1386                 string initpath = lyxrc.document_path;
1387
1388                 if (buffer_) {
1389                         string const trypath = buffer_->filePath();
1390                         // If directory is writeable, use this as default.
1391                         if (isDirWriteable(trypath))
1392                                 initpath = trypath;
1393                 }
1394
1395                 // FIXME UNICODE
1396                 FileDialog fileDlg(_("Select LyX document to insert"),
1397                         LFUN_FILE_INSERT,
1398                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1399                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1400
1401                 FileDialog::Result result =
1402                         fileDlg.open(from_utf8(initpath),
1403                                      FileFilterList(_("LyX Documents (*.lyx)")),
1404                                      docstring());
1405
1406                 if (result.first == FileDialog::Later)
1407                         return;
1408
1409                 // FIXME UNICODE
1410                 filename = to_utf8(result.second);
1411
1412                 // check selected filename
1413                 if (filename.empty()) {
1414                         // emit message signal.
1415                         message(_("Canceled."));
1416                         return;
1417                 }
1418         }
1419
1420         // Get absolute path of file and add ".lyx"
1421         // to the filename if necessary
1422         filename = fileSearch(string(), filename, "lyx");
1423
1424         docstring const disp_fn = makeDisplayPath(filename);
1425         // emit message signal.
1426         message(bformat(_("Inserting document %1$s..."), disp_fn));
1427
1428         docstring res;
1429         Buffer buf("", false);
1430         if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1431                 ErrorList & el = buffer_->errorList("Parse");
1432                 // Copy the inserted document error list into the current buffer one.
1433                 el = buf.errorList("Parse");
1434                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1435                                              buf.params().textclass, el);
1436                 res = _("Document %1$s inserted.");
1437         } else
1438                 res = _("Could not insert document %1$s");
1439
1440         // emit message signal.
1441         message(bformat(res, disp_fn));
1442         buffer_->errors("Parse");
1443         resize();
1444 }
1445
1446
1447 } // namespace lyx