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