]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
Change tracking:
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "buffer.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
28 #include "factory.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
32 #include "gettext.h"
33 #include "intl.h"
34 #include "insetiterator.h"
35 #include "language.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
38 #include "lyx_main.h"
39 #include "lyxfind.h"
40 #include "lyxfunc.h"
41 #include "lyxlayout.h"
42 #include "lyxtext.h"
43 #include "lyxtextclass.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "texrow.h"
51 #include "toc.h"
52 #include "undo.h"
53 #include "vspace.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
61
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
65
66 #include "graphics/Previews.h"
67
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
73
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
76
77 #include <functional>
78 #include <vector>
79
80
81 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 namespace Alert = lyx::frontend::Alert;
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_ = theBufferList().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 (theBufferList().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(theBufferList().getBuffer(s));
246                         return true;
247                 }
248                 // FIXME: should be LFUN_REVERT
249                 if (!theBufferList().close(theBufferList().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 = theBufferList().newBuffer(s);
258                 if (!::loadLyXFile(b, s)) {
259                         theBufferList().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 (theBufferList().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                 lyx::frontend::FontMetrics const & fm =
335                         theFontMetrics(cursor_.getFont());
336                 int const asc = fm.maxAscent();
337                 int const des = fm.maxDescent();
338                 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
339                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
340                         return false;
341         }
342         center();
343         return true;
344 }
345
346
347 bool BufferView::multiParSel()
348 {
349         if (!cursor_.selection())
350                 return false;
351         bool ret = multiparsel_cache_;
352         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
353         // Either this, or previous selection spans paragraphs
354         return ret || multiparsel_cache_;
355 }
356
357
358 bool BufferView::update(Update::flags flags)
359 {
360         // This is close to a hot-path.
361         if (lyxerr.debugging(Debug::DEBUG)) {
362                 lyxerr[Debug::DEBUG]
363                         << BOOST_CURRENT_FUNCTION
364                         << "[fitcursor = " << (flags & Update::FitCursor)
365                         << ", forceupdate = " << (flags & Update::Force)
366                         << ", singlepar = " << (flags & Update::SinglePar)
367                         << "]  buffer: " << buffer_ << endl;
368         }
369
370         // Check needed to survive LyX startup
371         if (!buffer_)
372                 return false;
373
374         // Update macro store
375         buffer_->buildMacros();
376
377         // First drawing step
378         updateMetrics(flags & Update::SinglePar);
379
380         // The second drawing step is done in WorkArea::redraw() if needed.
381         bool const need_second_step =
382                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
383                 && (fitCursor() || multiParSel());
384
385         return need_second_step;
386 }
387
388
389 void BufferView::updateScrollbar()
390 {
391         if (!buffer_) {
392                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
393                                      << " no text in updateScrollbar" << endl;
394                 scrollbarParameters_.reset();
395                 return;
396         }
397
398         LyXText & t = buffer_->text();
399         int const parsize = int(t.paragraphs().size() - 1);
400         if (anchor_ref_ >  parsize)  {
401                 anchor_ref_ = parsize;
402                 offset_ref_ = 0;
403         }
404
405         lyxerr[Debug::GUI]
406                 << BOOST_CURRENT_FUNCTION
407                 << " Updating scrollbar: height: " << t.paragraphs().size()
408                 << " curr par: " << cursor_.bottom().pit()
409                 << " default height " << defaultRowHeight() << endl;
410
411         // It would be better to fix the scrollbar to understand
412         // values in [0..1] and divide everything by wh
413
414         // estimated average paragraph height:
415         if (wh_ == 0)
416                 wh_ = height_ / 4;
417         int h = t.getPar(anchor_ref_).height();
418
419         // Normalize anchor/offset (MV):
420         while (offset_ref_ > h && anchor_ref_ < parsize) {
421                 anchor_ref_++;
422                 offset_ref_ -= h;
423                 h = t.getPar(anchor_ref_).height();
424         }
425         // Look at paragraph heights on-screen
426         int sumh = 0;
427         int nh = 0;
428         for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
429                 if (sumh > height_)
430                         break;
431                 int const h2 = t.getPar(pit).height();
432                 sumh += h2;
433                 nh++;
434         }
435         int const hav = sumh / nh;
436         // More realistic average paragraph height
437         if (hav > wh_)
438                 wh_ = hav;
439
440         scrollbarParameters_.height = (parsize + 1) * wh_;
441         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
442         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
443 }
444
445
446 ScrollbarParameters const & BufferView::scrollbarParameters() const
447 {
448         return scrollbarParameters_;
449 }
450
451
452 void BufferView::scrollDocView(int value)
453 {
454         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
455                            << "[ value = " << value << "]" << endl;
456
457         if (!buffer_)
458                 return;
459
460         LyXText & t = buffer_->text();
461
462         float const bar = value / float(wh_ * t.paragraphs().size());
463
464         anchor_ref_ = int(bar * t.paragraphs().size());
465         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
466                 anchor_ref_ = int(t.paragraphs().size()) - 1;
467         t.redoParagraph(anchor_ref_);
468         int const h = t.getPar(anchor_ref_).height();
469         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
470 }
471
472
473 void BufferView::setCursorFromScrollbar()
474 {
475         LyXText & t = buffer_->text();
476
477         int const height = 2 * defaultRowHeight();
478         int const first = height;
479         int const last = height_ - height;
480         LCursor & cur = cursor_;
481
482         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
483
484         switch (st) {
485         case bv_funcs::CUR_ABOVE:
486                 t.setCursorFromCoordinates(cur, 0, first);
487                 cur.clearSelection();
488                 break;
489         case bv_funcs::CUR_BELOW:
490                 t.setCursorFromCoordinates(cur, 0, last);
491                 cur.clearSelection();
492                 break;
493         case bv_funcs::CUR_INSIDE:
494                 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
495                 int const newy = min(last, max(y, first));
496                 if (y != newy) {
497                         cur.reset(buffer_->inset());
498                         t.setCursorFromCoordinates(cur, 0, newy);
499                 }
500         }
501 }
502
503
504 Change const BufferView::getCurrentChange() const
505 {
506         if (!cursor_.selection())
507                 return Change(Change::UNCHANGED);
508
509         DocIterator dit = cursor_.selectionBegin();
510         return dit.paragraph().lookupChange(dit.pos());
511 }
512
513
514 void BufferView::savePosition(unsigned int i)
515 {
516         if (i >= saved_positions_num)
517                 return;
518         BOOST_ASSERT(cursor_.inTexted());
519         saved_positions[i] = Position(buffer_->fileName(),
520                                       cursor_.paragraph().id(),
521                                       cursor_.pos());
522         if (i > 0)
523                 // emit message signal.
524                 message(bformat(_("Saved bookmark %1$d"), i));
525 }
526
527
528 void BufferView::restorePosition(unsigned int i)
529 {
530         if (i >= saved_positions_num)
531                 return;
532
533         string const fname = saved_positions[i].filename;
534
535         cursor_.clearSelection();
536
537         if (fname != buffer_->fileName()) {
538                 Buffer * b = 0;
539                 if (theBufferList().exists(fname))
540                         b = theBufferList().getBuffer(fname);
541                 else {
542                         b = theBufferList().newBuffer(fname);
543                         // Don't ask, just load it
544                         ::loadLyXFile(b, fname);
545                 }
546                 if (b)
547                         setBuffer(b);
548         }
549
550         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
551         if (par == buffer_->par_iterator_end())
552                 return;
553
554         setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
555
556         if (i > 0)
557                 // emit message signal.
558                 message(bformat(_("Moved to bookmark %1$d"), i));
559 }
560
561
562 bool BufferView::isSavedPosition(unsigned int i)
563 {
564         return i < saved_positions_num && !saved_positions[i].filename.empty();
565 }
566
567 void BufferView::saveSavedPositions()
568 {
569         // save bookmarks. It is better to use the pit interface
570         // but I do not know how to effectively convert between
571         // par_id and pit.
572         for (unsigned int i=1; i < saved_positions_num; ++i) {
573                 if ( isSavedPosition(i) )
574                         LyX::ref().session().saveBookmark( boost::tie(
575                                 i,
576                                 saved_positions[i].filename,
577                                 saved_positions[i].par_id,
578                                 saved_positions[i].par_pos) );
579         }
580 }
581
582 void BufferView::switchKeyMap()
583 {
584         if (!lyxrc.rtl_support)
585                 return;
586
587         if (getLyXText()->real_current_font.isRightToLeft()) {
588                 if (intl_->keymap == Intl::PRIMARY)
589                         intl_->keyMapSec();
590         } else {
591                 if (intl_->keymap == Intl::SECONDARY)
592                         intl_->keyMapPrim();
593         }
594 }
595
596
597 int BufferView::workWidth() const
598 {
599         return width_;
600 }
601
602
603 void BufferView::center()
604 {
605         CursorSlice & bot = cursor_.bottom();
606         lyx::pit_type const pit = bot.pit();
607         bot.text()->redoParagraph(pit);
608         Paragraph const & par = bot.text()->paragraphs()[pit];
609         anchor_ref_ = pit;
610         offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
611                 + par.ascent() - height_ / 2;
612 }
613
614
615 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
616 {
617         FuncStatus flag;
618
619         switch (cmd.action) {
620
621         case LFUN_UNDO:
622                 flag.enabled(!buffer_->undostack().empty());
623                 break;
624         case LFUN_REDO:
625                 flag.enabled(!buffer_->redostack().empty());
626                 break;
627         case LFUN_FILE_INSERT:
628         case LFUN_FILE_INSERT_ASCII_PARA:
629         case LFUN_FILE_INSERT_ASCII:
630         case LFUN_BOOKMARK_SAVE:
631                 // FIXME: Actually, these LFUNS should be moved to LyXText
632                 flag.enabled(cursor_.inTexted());
633                 break;
634         case LFUN_FONT_STATE:
635         case LFUN_LABEL_INSERT:
636         case LFUN_PARAGRAPH_GOTO:
637         // FIXME handle non-trivially
638         case LFUN_OUTLINE_UP:
639         case LFUN_OUTLINE_DOWN:
640         case LFUN_OUTLINE_IN:
641         case LFUN_OUTLINE_OUT:
642         case LFUN_NOTE_NEXT:
643         case LFUN_REFERENCE_NEXT:
644         case LFUN_WORD_FIND:
645         case LFUN_WORD_REPLACE:
646         case LFUN_MARK_OFF:
647         case LFUN_MARK_ON:
648         case LFUN_MARK_TOGGLE:
649         case LFUN_SCREEN_RECENTER:
650         case LFUN_BIBTEX_DATABASE_ADD:
651         case LFUN_BIBTEX_DATABASE_DEL:
652         case LFUN_WORDS_COUNT:
653         case LFUN_NEXT_INSET_TOGGLE:
654                 flag.enabled(true);
655                 break;
656
657         case LFUN_LABEL_GOTO: {
658                 flag.enabled(!cmd.argument().empty()
659                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
660                 break;
661         }
662
663         case LFUN_BOOKMARK_GOTO:
664                 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
665                 break;
666
667         case LFUN_CHANGES_TRACK:
668                 flag.enabled(true);
669                 flag.setOnOff(buffer_->params().trackChanges);
670                 break;
671
672         case LFUN_CHANGES_OUTPUT: {
673                 OutputParams runparams;
674                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
675                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
676                 flag.setOnOff(buffer_->params().outputChanges);
677                 break;
678         }
679
680         case LFUN_CHANGES_MERGE:
681         case LFUN_CHANGE_NEXT:
682         case LFUN_ALL_CHANGES_ACCEPT:
683         case LFUN_ALL_CHANGES_REJECT:
684                 flag.enabled(buffer_); // FIXME: Change tracking (MG)
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                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
837                 break;
838
839         case LFUN_CHANGES_OUTPUT: {
840                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
841                 break;
842         }
843
844         case LFUN_CHANGE_NEXT:
845                 lyx::find::findNextChange(this);
846                 break;
847
848         case LFUN_CHANGES_MERGE:
849                 if (lyx::find::findNextChange(this))
850                         showDialog("changes");
851                 break;
852
853         case LFUN_ALL_CHANGES_ACCEPT: {
854                 cursor_.reset(buffer_->inset());
855 #ifdef WITH_WARNINGS
856 #warning FIXME changes
857 #endif
858                 while (lyx::find::findNextChange(this))
859                         getLyXText()->acceptChange(cursor_);
860                 update();
861                 break;
862         }
863
864         case LFUN_ALL_CHANGES_REJECT: {
865                 cursor_.reset(buffer_->inset());
866 #ifdef WITH_WARNINGS
867 #warning FIXME changes
868 #endif
869                 while (lyx::find::findNextChange(this))
870                         getLyXText()->rejectChange(cursor_);
871                 break;
872         }
873
874         case LFUN_WORD_FIND:
875                 lyx::find::find(this, cmd);
876                 break;
877
878         case LFUN_WORD_REPLACE:
879                 lyx::find::replace(this, cmd);
880                 break;
881
882         case LFUN_MARK_OFF:
883                 cur.clearSelection();
884                 cur.resetAnchor();
885                 cur.message(lyx::from_utf8(N_("Mark off")));
886                 break;
887
888         case LFUN_MARK_ON:
889                 cur.clearSelection();
890                 cur.mark() = true;
891                 cur.resetAnchor();
892                 cur.message(lyx::from_utf8(N_("Mark on")));
893                 break;
894
895         case LFUN_MARK_TOGGLE:
896                 cur.clearSelection();
897                 if (cur.mark()) {
898                         cur.mark() = false;
899                         cur.message(lyx::from_utf8(N_("Mark removed")));
900                 } else {
901                         cur.mark() = true;
902                         cur.message(lyx::from_utf8(N_("Mark set")));
903                 }
904                 cur.resetAnchor();
905                 break;
906
907         case LFUN_SCREEN_RECENTER:
908                 center();
909                 break;
910
911         case LFUN_BIBTEX_DATABASE_ADD: {
912                 LCursor tmpcur = cursor_;
913                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
914                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
915                                                 InsetBase::BIBTEX_CODE);
916                 if (inset) {
917                         if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
918                                 buffer_->updateBibfilesCache();
919                 }
920                 break;
921         }
922
923         case LFUN_BIBTEX_DATABASE_DEL: {
924                 LCursor tmpcur = cursor_;
925                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
926                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
927                                                 InsetBase::BIBTEX_CODE);
928                 if (inset) {
929                         if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
930                                 buffer_->updateBibfilesCache();
931                 }
932                 break;
933         }
934
935         case LFUN_WORDS_COUNT: {
936                 DocIterator from, to;
937                 if (cur.selection()) {
938                         from = cur.selectionBegin();
939                         to = cur.selectionEnd();
940                 } else {
941                         from = doc_iterator_begin(buffer_->inset());
942                         to = doc_iterator_end(buffer_->inset());
943                 }
944                 int const count = countWords(from, to);
945                 docstring message;
946                 if (count != 1) {
947                         if (cur.selection())
948                                 message = bformat(_("%1$d words in selection."),
949                                           count);
950                                 else
951                                         message = bformat(_("%1$d words in document."),
952                                                           count);
953                 }
954                 else {
955                         if (cur.selection())
956                                 message = _("One word in selection.");
957                         else
958                                 message = _("One word in document.");
959                 }
960
961                 Alert::information(_("Count words"), message);
962         }
963                 break;
964
965         case LFUN_BUFFER_TOGGLE_COMPRESSION:
966                 // turn compression on/off
967                 buffer_->params().compressed = !buffer_->params().compressed;
968                 break;
969
970         case LFUN_NEXT_INSET_TOGGLE: {
971                 // this is the real function we want to invoke
972                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
973                 // if there is an inset at cursor, see whether it
974                 // wants to toggle.
975                 InsetBase * inset = cur.nextInset();
976                 if (inset && inset->isActive()) {
977                         LCursor tmpcur = cur;
978                         tmpcur.pushLeft(*inset);
979                         inset->dispatch(tmpcur, tmpcmd);
980                         if (tmpcur.result().dispatched()) {
981                                 cur.dispatched();
982                         }
983                 }
984                 // if it did not work, try the underlying inset.
985                 if (!cur.result().dispatched())
986                         cur.dispatch(tmpcmd);
987
988                 if (cur.result().dispatched())
989                         cur.clearSelection();
990
991                 break;
992         }
993
994         default:
995                 return false;
996         }
997
998         return true;
999 }
1000
1001
1002 docstring const BufferView::requestSelection()
1003 {
1004         if (!buffer_)
1005                 return docstring();
1006
1007         LCursor & cur = cursor_;
1008
1009         if (!cur.selection()) {
1010                 xsel_cache_.set = false;
1011                 return docstring();
1012         }
1013
1014         if (!xsel_cache_.set ||
1015             cur.top() != xsel_cache_.cursor ||
1016             cur.anchor_.top() != xsel_cache_.anchor)
1017         {
1018                 xsel_cache_.cursor = cur.top();
1019                 xsel_cache_.anchor = cur.anchor_.top();
1020                 xsel_cache_.set = cur.selection();
1021                 return cur.selectionAsString(false);
1022         }
1023         return docstring();
1024 }
1025
1026
1027 void BufferView::clearSelection()
1028 {
1029         if (buffer_) {
1030                 cursor_.clearSelection();
1031                 xsel_cache_.set = false;
1032         }
1033 }
1034
1035
1036 void BufferView::workAreaResize(int width, int height)
1037 {
1038         bool const widthChange = width != width_;
1039         bool const heightChange = height != height_;
1040
1041         // Update from work area
1042         width_ = width;
1043         height_ = height;
1044
1045         if (buffer_ && widthChange) {
1046                 // The WorkArea content needs a resize
1047                 resize();
1048         }
1049
1050         if (widthChange || heightChange)
1051                 update();
1052 }
1053
1054
1055 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1056 {
1057         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1058
1059         // This is only called for mouse related events including
1060         // LFUN_FILE_OPEN generated by drag-and-drop.
1061         FuncRequest cmd = cmd0;
1062
1063         if (!buffer_)
1064                 return false;
1065
1066         LCursor cur(*this);
1067         cur.push(buffer_->inset());
1068         cur.selection() = cursor_.selection();
1069
1070         // Doesn't go through lyxfunc, so we need to update
1071         // the layout choice etc. ourselves
1072
1073         // E.g. Qt mouse press when no buffer
1074         if (!buffer_)
1075                 return false;
1076
1077         // Either the inset under the cursor or the
1078         // surrounding LyXText will handle this event.
1079
1080         // Build temporary cursor.
1081         cmd.y = min(max(cmd.y, -1), height_);
1082         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1083         //lyxerr << BOOST_CURRENT_FUNCTION
1084         //       << " * hit inset at tip: " << inset << endl;
1085         //lyxerr << BOOST_CURRENT_FUNCTION
1086         //       << " * created temp cursor:" << cur << endl;
1087
1088         // Put anchor at the same position.
1089         cur.resetAnchor();
1090
1091         // Try to dispatch to an non-editable inset near this position
1092         // via the temp cursor. If the inset wishes to change the real
1093         // cursor it has to do so explicitly by using
1094         //  cur.bv().cursor() = cur;  (or similar)
1095         if (inset)
1096                 inset->dispatch(cur, cmd);
1097
1098         // Now dispatch to the temporary cursor. If the real cursor should
1099         // be modified, the inset's dispatch has to do so explicitly.
1100         if (!cur.result().dispatched())
1101                 cur.dispatch(cmd);
1102
1103         if (cur.result().dispatched()) {
1104                 // Redraw if requested or necessary.
1105                 if (cur.result().update())
1106                         update(Update::FitCursor | Update::Force);
1107                 else
1108                         update(Update::FitCursor | Update::MultiParSel);
1109         }
1110
1111         return true;
1112 }
1113
1114
1115 void BufferView::scroll(int lines)
1116 {
1117 //      if (!buffer_)
1118 //              return;
1119 //
1120 //      LyXText const * t = &buffer_->text();
1121 //      int const line_height = defaultRowHeight();
1122 //
1123 //      // The new absolute coordinate
1124 //      int new_top_y = top_y() + lines * line_height;
1125 //
1126 //      // Restrict to a valid value
1127 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1128 //      new_top_y = std::max(0, new_top_y);
1129 //
1130 //      scrollDocView(new_top_y);
1131 //
1132 //      // Update the scrollbar.
1133 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1134 }
1135
1136
1137 void BufferView::setCursorFromRow(int row)
1138 {
1139         int tmpid = -1;
1140         int tmppos = -1;
1141
1142         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1143
1144         if (tmpid == -1)
1145                 buffer_->text().setCursor(cursor_, 0, 0);
1146         else
1147                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1148 }
1149
1150
1151 void BufferView::gotoLabel(string const & label)
1152 {
1153         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1154                 vector<string> labels;
1155                 it->getLabelList(*buffer_, labels);
1156                 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1157                         setCursor(it);
1158                         update();
1159                         return;
1160                 }
1161         }
1162 }
1163
1164
1165 LyXText * BufferView::getLyXText()
1166 {
1167         LyXText * text = cursor_.innerText();
1168         BOOST_ASSERT(text);
1169         return text;
1170 }
1171
1172
1173 LyXText const * BufferView::getLyXText() const
1174 {
1175         LyXText const * text = cursor_.innerText();
1176         BOOST_ASSERT(text);
1177         return text;
1178 }
1179
1180
1181 int BufferView::workHeight() const
1182 {
1183         return height_;
1184 }
1185
1186
1187 void BufferView::setCursor(DocIterator const & dit)
1188 {
1189         size_t const n = dit.depth();
1190         for (size_t i = 0; i < n; ++i)
1191                 dit[i].inset().edit(cursor_, true);
1192
1193         cursor_.setCursor(dit);
1194         cursor_.selection() = false;
1195 }
1196
1197
1198 void BufferView::mouseSetCursor(LCursor & cur)
1199 {
1200         BOOST_ASSERT(&cur.bv() == this);
1201
1202         // Has the cursor just left the inset?
1203         bool badcursor = false;
1204         if (&cursor_.inset() != &cur.inset())
1205                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1206
1207         // do the dEPM magic if needed
1208         // FIXME: move this to InsetText::notifyCursorLeaves?
1209         if (!badcursor && cursor_.inTexted())
1210                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1211
1212         cursor_ = cur;
1213         cursor_.clearSelection();
1214         cursor_.setTargetX();
1215         finishUndo();
1216
1217 }
1218
1219
1220 void BufferView::putSelectionAt(DocIterator const & cur,
1221                                 int length, bool backwards)
1222 {
1223         cursor_.clearSelection();
1224
1225         setCursor(cur);
1226
1227         if (length) {
1228                 if (backwards) {
1229                         cursor_.pos() += length;
1230                         cursor_.setSelection(cursor_, -length);
1231                 } else
1232                         cursor_.setSelection(cursor_, length);
1233         }
1234 }
1235
1236
1237 LCursor & BufferView::cursor()
1238 {
1239         return cursor_;
1240 }
1241
1242
1243 LCursor const & BufferView::cursor() const
1244 {
1245         return cursor_;
1246 }
1247
1248
1249 lyx::pit_type BufferView::anchor_ref() const
1250 {
1251         return anchor_ref_;
1252 }
1253
1254
1255 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1256 {
1257         return metrics_info_;
1258 }
1259
1260
1261 void BufferView::updateMetrics(bool singlepar)
1262 {
1263         // Remove old position cache
1264         theCoords.clear();
1265         LyXText & buftext = buffer_->text();
1266         lyx::pit_type size = int(buftext.paragraphs().size());
1267
1268         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1269                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1270                 offset_ref_ = 0;
1271         }
1272
1273         lyx::pit_type const pit = anchor_ref_;
1274         int pit1 = pit;
1275         int pit2 = pit;
1276         size_t const npit = buftext.paragraphs().size();
1277
1278         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1279         // the (main text, not inset!) paragraph containing the cursor.
1280         // (if this paragraph contains insets etc., rebreaking will
1281         // recursively descend)
1282         if (!singlepar || pit == cursor_.bottom().pit())
1283                 buftext.redoParagraph(pit);
1284         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1285
1286         // Redo paragraphs above anchor if necessary; again, in Single Par
1287         // mode, only if we encounter the (main text) one having the cursor.
1288         int y1 = y0;
1289         while (y1 > 0 && pit1 > 0) {
1290                 y1 -= buftext.getPar(pit1).ascent();
1291                 --pit1;
1292                 if (!singlepar || pit1 == cursor_.bottom().pit())
1293                         buftext.redoParagraph(pit1);
1294                 y1 -= buftext.getPar(pit1).descent();
1295         }
1296
1297
1298         // Take care of ascent of first line
1299         y1 -= buftext.getPar(pit1).ascent();
1300
1301         // Normalize anchor for next time
1302         anchor_ref_ = pit1;
1303         offset_ref_ = -y1;
1304
1305         // Grey at the beginning is ugly
1306         if (pit1 == 0 && y1 > 0) {
1307                 y0 -= y1;
1308                 y1 = 0;
1309                 anchor_ref_ = 0;
1310         }
1311
1312         // Redo paragraphs below the anchor if necessary. Single par mode:
1313         // only the one containing the cursor if encountered.
1314         int y2 = y0;
1315         while (y2 < height_ && pit2 < int(npit) - 1) {
1316                 y2 += buftext.getPar(pit2).descent();
1317                 ++pit2;
1318                 if (!singlepar || pit2 == cursor_.bottom().pit())
1319                         buftext.redoParagraph(pit2);
1320                 y2 += buftext.getPar(pit2).ascent();
1321         }
1322
1323         // Take care of descent of last line
1324         y2 += buftext.getPar(pit2).descent();
1325
1326         // The coordinates of all these paragraphs are correct, cache them
1327         int y = y1;
1328         CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1329         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1330                 Paragraph const & par = buftext.getPar(pit);
1331                 y += par.ascent();
1332                 parPos[pit] = Point(0, y);
1333                 if (singlepar && pit == cursor_.bottom().pit()) {
1334                         // In Single Paragraph mode, collect here the
1335                         // y1 and y2 of the (one) paragraph the cursor is in
1336                         y1 = y - par.ascent();
1337                         y2 = y + par.descent();
1338                 }
1339                 y += par.descent();
1340         }
1341
1342         if (singlepar) {
1343                 // collect cursor paragraph iter bounds
1344                 pit1 = cursor_.bottom().pit();
1345                 pit2 = cursor_.bottom().pit();
1346         }
1347
1348         lyxerr[Debug::DEBUG]
1349                 << BOOST_CURRENT_FUNCTION
1350                 << " y1: " << y1
1351                 << " y2: " << y2
1352                 << " pit1: " << pit1
1353                 << " pit2: " << pit2
1354                 << " npit: " << npit
1355                 << " singlepar: " << singlepar
1356                 << "size: " << size
1357                 << endl;
1358
1359         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1360 }
1361
1362
1363 void BufferView::menuInsertLyXFile(string const & filenm)
1364 {
1365         BOOST_ASSERT(cursor_.inTexted());
1366         string filename = filenm;
1367
1368         if (filename.empty()) {
1369                 // Launch a file browser
1370                 // FIXME UNICODE
1371                 string initpath = lyxrc.document_path;
1372
1373                 if (buffer_) {
1374                         string const trypath = buffer_->filePath();
1375                         // If directory is writeable, use this as default.
1376                         if (isDirWriteable(trypath))
1377                                 initpath = trypath;
1378                 }
1379
1380                 // FIXME UNICODE
1381                 FileDialog fileDlg(_("Select LyX document to insert"),
1382                         LFUN_FILE_INSERT,
1383                         make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
1384                         make_pair(_("Examples|#E#e"), lyx::from_utf8(addPath(package().system_support(), "examples"))));
1385
1386                 FileDialog::Result result =
1387                         fileDlg.open(lyx::from_utf8(initpath),
1388                                      FileFilterList(_("LyX Documents (*.lyx)")),
1389                                      docstring());
1390
1391                 if (result.first == FileDialog::Later)
1392                         return;
1393
1394                 // FIXME UNICODE
1395                 filename = lyx::to_utf8(result.second);
1396
1397                 // check selected filename
1398                 if (filename.empty()) {
1399                         // emit message signal.
1400                         message(_("Canceled."));
1401                         return;
1402                 }
1403         }
1404
1405         // Get absolute path of file and add ".lyx"
1406         // to the filename if necessary
1407         filename = fileSearch(string(), filename, "lyx");
1408
1409         docstring const disp_fn = makeDisplayPath(filename);
1410         // emit message signal.
1411         message(bformat(_("Inserting document %1$s..."), disp_fn));
1412
1413         docstring res;
1414         Buffer buf("", false);
1415         if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1416                 ErrorList & el = buffer_->errorList("Parse");
1417                 // Copy the inserted document error list into the current buffer one.
1418                 el = buf.errorList("Parse");
1419                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1420                                              buf.params().textclass, el);
1421                 res = _("Document %1$s inserted.");
1422         } else
1423                 res = _("Could not insert document %1$s");
1424
1425         // emit message signal.
1426         message(bformat(res, disp_fn));
1427         buffer_->errors("Parse");
1428         resize();
1429 }