2 * \file buffer_funcs.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
20 #include "DocIterator.h"
22 #include "ErrorList.h"
24 #include "FloatList.h"
28 #include "TextClass.h"
29 #include "Paragraph.h"
30 #include "paragraph_funcs.h"
31 #include "ParagraphList.h"
32 #include "ParagraphParameters.h"
33 #include "ParIterator.h"
36 #include "TocBackend.h"
37 #include "VCBackend.h"
39 #include "frontends/alert.h"
41 #include "insets/InsetBibitem.h"
42 #include "insets/InsetCaption.h"
43 #include "insets/InsetInclude.h"
44 #include "insets/InsetTabular.h"
46 #include "support/convert.h"
47 #include "support/filetools.h"
48 #include "support/fs_extras.h"
49 #include "support/lyxlib.h"
51 #include <boost/bind.hpp>
52 #include <boost/filesystem/operations.hpp>
62 using support::bformat;
63 using support::FileName;
64 using support::libFileSearch;
65 using support::makeAbsPath;
66 using support::makeDisplayPath;
67 using support::onlyFilename;
68 using support::onlyPath;
69 using support::unlink;
71 namespace Alert = frontend::Alert;
72 namespace fs = boost::filesystem;
76 bool readFile(Buffer * const b, FileName const & s)
80 // File information about normal file
81 if (!fs::exists(s.toFilesystemEncoding())) {
82 docstring const file = makeDisplayPath(s.absFilename(), 50);
83 docstring text = bformat(_("The specified document\n%1$s"
84 "\ncould not be read."), file);
85 Alert::error(_("Could not read document"), text);
89 // Check if emergency save file exists and is newer.
90 FileName const e(s.absFilename() + ".emergency");
92 if (fs::exists(e.toFilesystemEncoding()) &&
93 fs::exists(s.toFilesystemEncoding()) &&
94 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
96 docstring const file = makeDisplayPath(s.absFilename(), 20);
97 docstring const text =
98 bformat(_("An emergency save of the document "
100 "Recover emergency save?"), file);
101 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
102 _("&Recover"), _("&Load Original"),
106 // the file is not saved if we load the emergency file.
108 return b->readFile(e);
116 // Now check if autosave file is newer.
117 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
119 if (fs::exists(a.toFilesystemEncoding()) &&
120 fs::exists(s.toFilesystemEncoding()) &&
121 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
123 docstring const file = makeDisplayPath(s.absFilename(), 20);
124 docstring const text =
125 bformat(_("The backup of the document "
126 "%1$s is newer.\n\nLoad the "
127 "backup instead?"), file);
128 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
129 _("&Load backup"), _("Load &original"),
133 // the file is not saved if we load the autosave file.
135 return b->readFile(a);
137 // Here we delete the autosave
144 return b->readFile(s);
152 bool loadLyXFile(Buffer * b, FileName const & s)
156 if (fs::is_readable(s.toFilesystemEncoding())) {
157 if (readFile(b, s)) {
158 b->lyxvc().file_found_hook(s);
159 if (!fs::is_writable(s.toFilesystemEncoding()))
160 b->setReadonly(true);
164 docstring const file = makeDisplayPath(s.absFilename(), 20);
165 // Here we probably should run
166 if (LyXVC::file_not_found_hook(s)) {
167 docstring const text =
168 bformat(_("Do you want to retrieve the document"
169 " %1$s from version control?"), file);
170 int const ret = Alert::prompt(_("Retrieve from version control?"),
171 text, 0, 1, _("&Retrieve"), _("&Cancel"));
174 // How can we know _how_ to do the checkout?
175 // With the current VC support it has to be,
176 // a RCS file since CVS do not have special ,v files.
178 return loadLyXFile(b, s);
186 bool checkIfLoaded(FileName const & fn)
188 return theBufferList().getBuffer(fn.absFilename());
192 Buffer * checkAndLoadLyXFile(FileName const & filename)
194 // File already open?
195 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
197 if (checkBuffer->isClean())
199 docstring const file = makeDisplayPath(filename.absFilename(), 20);
200 docstring text = bformat(_(
201 "The document %1$s is already loaded and has unsaved changes.\n"
202 "Do you want to abandon your changes and reload the version on disk?"), file);
203 if (Alert::prompt(_("Reload saved document?"),
204 text, 0, 1, _("&Reload"), _("&Keep Changes")))
207 // FIXME: should be LFUN_REVERT
208 if (theBufferList().close(checkBuffer, false))
210 return checkAndLoadLyXFile(filename);
212 // The file could not be closed.
216 if (isFileReadable(filename)) {
217 Buffer * b = theBufferList().newBuffer(filename.absFilename());
218 if (!lyx::loadLyXFile(b, filename)) {
219 theBufferList().release(b);
225 docstring text = bformat(_("The document %1$s does not yet "
226 "exist.\n\nDo you want to create a new document?"),
227 from_utf8(filename.absFilename()));
228 if (!Alert::prompt(_("Create new document?"),
229 text, 0, 1, _("&Create"), _("Cancel")))
230 return newFile(filename.absFilename(), string(), true);
235 // FIXME newFile() should probably be a member method of Application...
236 Buffer * newFile(string const & filename, string const & templatename,
240 Buffer * b = theBufferList().newBuffer(filename);
244 // use defaults.lyx as a default template if it exists.
245 if (templatename.empty())
246 tname = libFileSearch("templates", "defaults.lyx");
248 tname = makeAbsPath(templatename);
250 if (!tname.empty()) {
251 if (!b->readFile(tname)) {
252 docstring const file = makeDisplayPath(tname.absFilename(), 50);
253 docstring const text = bformat(
254 _("The specified document template\n%1$s\ncould not be read."),
256 Alert::error(_("Could not read template"), text);
257 theBufferList().release(b);
264 b->setFileName(filename);
267 b->setReadonly(false);
268 b->fully_loaded(true);
274 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
275 ErrorList & errorList)
277 TeXErrors::Errors::const_iterator cit = terr.begin();
278 TeXErrors::Errors::const_iterator end = terr.end();
280 for (; cit != end; ++cit) {
283 int errorrow = cit->error_in_line;
284 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
290 found = buf.texrow().getIdFromRow(errorrow, id_end,
292 } while (found && id_start == id_end && pos_start == pos_end);
294 errorList.push_back(ErrorItem(cit->error_desc,
295 cit->error_text, id_start, pos_start, pos_end));
300 string const bufferFormat(Buffer const & buffer)
302 if (buffer.isDocBook())
304 else if (buffer.isLiterate())
311 int countWords(DocIterator const & from, DocIterator const & to)
315 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
316 // Copied and adapted from isLetter() in ControlSpellChecker
318 && dit.pos() != dit.lastpos()
319 && dit.paragraph().isLetter(dit.pos())
320 && !dit.paragraph().isDeleted(dit.pos())) {
335 depth_type getDepth(DocIterator const & it)
337 depth_type depth = 0;
338 for (size_t i = 0 ; i < it.depth() ; ++i)
339 if (!it[i].inset().inMathed())
340 depth += it[i].paragraph().getDepth() + 1;
341 // remove 1 since the outer inset does not count
345 depth_type getItemDepth(ParIterator const & it)
347 Paragraph const & par = *it;
348 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
350 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
353 // this will hold the lowest depth encountered up to now.
354 depth_type min_depth = getDepth(it);
355 ParIterator prev_it = it;
358 --prev_it.top().pit();
360 // start of nested inset: go to outer par
362 if (prev_it.empty()) {
363 // start of document: nothing to do
368 // We search for the first paragraph with same label
369 // that is not more deeply nested.
370 Paragraph & prev_par = *prev_it;
371 depth_type const prev_depth = getDepth(prev_it);
372 if (labeltype == prev_par.layout()->labeltype) {
373 if (prev_depth < min_depth) {
374 return prev_par.itemdepth + 1;
376 else if (prev_depth == min_depth) {
377 return prev_par.itemdepth;
380 min_depth = std::min(min_depth, prev_depth);
381 // small optimization: if we are at depth 0, we won't
382 // find anything else
383 if (prev_depth == 0) {
390 bool needEnumCounterReset(ParIterator const & it)
392 Paragraph const & par = *it;
393 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
394 depth_type const cur_depth = par.getDepth();
395 ParIterator prev_it = it;
396 while (prev_it.pit()) {
397 --prev_it.top().pit();
398 Paragraph const & prev_par = *prev_it;
399 if (prev_par.getDepth() <= cur_depth)
400 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
402 // start of nested inset: reset
407 // set the label of a paragraph. This includes the counters.
408 void setLabel(Buffer const & buf, ParIterator & it)
410 TextClass const & textclass = buf.params().getTextClass();
411 Paragraph & par = it.paragraph();
412 Layout_ptr const & layout = par.layout();
413 Counters & counters = textclass.counters();
415 if (par.params().startOfAppendix()) {
416 // FIXME: only the counter corresponding to toplevel
417 // sectionning should be reset
419 counters.appendix(true);
421 par.params().appendix(counters.appendix());
423 // Compute the item depth of the paragraph
424 par.itemdepth = getItemDepth(it);
426 if (layout->margintype == MARGIN_MANUAL) {
427 if (par.params().labelWidthString().empty())
428 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
430 par.params().labelWidthString(docstring());
433 // is it a layout that has an automatic label?
434 if (layout->labeltype == LABEL_COUNTER) {
435 if (layout->toclevel <= buf.params().secnumdepth
436 && (layout->latextype != LATEX_ENVIRONMENT
437 || isFirstInSequence(it.pit(), it.plist()))) {
438 counters.step(layout->counter);
439 par.params().labelString(
440 par.expandLabel(layout, buf.params()));
442 par.params().labelString(docstring());
444 } else if (layout->labeltype == LABEL_ITEMIZE) {
445 // At some point of time we should do something more
446 // clever here, like:
447 // par.params().labelString(
448 // buf.params().user_defined_bullet(par.itemdepth).getText());
449 // for now, use a simple hardcoded label
451 switch (par.itemdepth) {
453 itemlabel = char_type(0x2022);
456 itemlabel = char_type(0x2013);
459 itemlabel = char_type(0x2217);
462 itemlabel = char_type(0x2219); // or 0x00b7
465 par.params().labelString(itemlabel);
467 } else if (layout->labeltype == LABEL_ENUMERATE) {
469 // Yes I know this is a really, really! bad solution
471 docstring enumcounter = from_ascii("enum");
473 switch (par.itemdepth) {
485 // not a valid enumdepth...
489 // Maybe we have to reset the enumeration counter.
490 if (needEnumCounterReset(it))
491 counters.reset(enumcounter);
493 counters.step(enumcounter);
497 switch (par.itemdepth) {
499 format = N_("\\arabic{enumi}.");
502 format = N_("(\\alph{enumii})");
505 format = N_("\\roman{enumiii}.");
508 format = N_("\\Alph{enumiv}.");
511 // not a valid enumdepth...
515 par.params().labelString(counters.counterLabel(
516 par.translateIfPossible(from_ascii(format), buf.params())));
518 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
519 counters.step(from_ascii("bibitem"));
520 int number = counters.value(from_ascii("bibitem"));
522 par.bibitem()->setCounter(number);
524 par.params().labelString(
525 par.translateIfPossible(layout->labelstring(), buf.params()));
526 // In biblio shouldn't be following counters but...
527 } else if (layout->labeltype == LABEL_SENSITIVE) {
528 string const & type = counters.current_float();
529 docstring full_label;
531 full_label = buf.B_("Senseless!!! ");
533 docstring name = buf.B_(textclass.floats().getType(type).name());
534 if (counters.hasCounter(from_utf8(type))) {
535 counters.step(from_utf8(type));
536 full_label = bformat(from_ascii("%1$s %2$s:"),
538 convert<docstring>(counters.value(from_utf8(type))));
540 full_label = bformat(from_ascii("%1$s #:"), name);
542 par.params().labelString(full_label);
544 } else if (layout->labeltype == LABEL_NO_LABEL)
545 par.params().labelString(docstring());
547 par.params().labelString(
548 par.translateIfPossible(layout->labelstring(), buf.params()));
553 void updateLabels(Buffer const & buf, ParIterator & parit)
555 BOOST_ASSERT(parit.pit() == 0);
557 depth_type maxdepth = 0;
558 pit_type const lastpit = parit.lastpit();
559 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
560 // reduce depth if necessary
561 parit->params().depth(min(parit->params().depth(), maxdepth));
562 maxdepth = parit->getMaxDepthAfter();
564 // set the counter for this paragraph
565 setLabel(buf, parit);
568 InsetList::const_iterator iit = parit->insetlist.begin();
569 InsetList::const_iterator end = parit->insetlist.end();
570 for (; iit != end; ++iit) {
571 parit.pos() = iit->pos;
572 iit->inset->updateLabels(buf, parit);
579 void updateLabels(Buffer const & buf, bool childonly)
581 Buffer const * const master = buf.getMasterBuffer();
582 // Use the master text class also for child documents
583 TextClass const & textclass = master->params().getTextClass();
586 // If this is a child document start with the master
587 if (master != &buf) {
588 updateLabels(*master);
592 // start over the counters
593 textclass.counters().reset();
597 ParIterator parit = par_iterator_begin(buf.inset());
599 updateLabels(buf, parit);
601 Buffer & cbuf = const_cast<Buffer &>(buf);
602 cbuf.tocBackend().update();
604 cbuf.structureChanged();
608 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
610 if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
611 Buffer * master = buffer.getMasterBuffer();
612 master->tocBackend().updateItem(par_it);
613 master->structureChanged();