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