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"
19 #include "dociterator.h"
21 #include "errorlist.h"
23 #include "FloatList.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
35 #include "TocBackend.h"
36 #include "vc-backend.h"
38 #include "frontends/Alert.h"
40 #include "insets/insetbibitem.h"
41 #include "insets/insetinclude.h"
43 #include "support/filetools.h"
44 #include "support/fs_extras.h"
45 #include "support/lyxlib.h"
47 #include <boost/bind.hpp>
48 #include <boost/filesystem/operations.hpp>
55 using support::bformat;
56 using support::FileName;
57 using support::libFileSearch;
58 using support::makeDisplayPath;
59 using support::onlyFilename;
60 using support::onlyPath;
61 using support::unlink;
66 namespace Alert = frontend::Alert;
67 namespace fs = boost::filesystem;
71 bool readFile(Buffer * const b, FileName const & s)
75 // File information about normal file
76 if (!fs::exists(s.toFilesystemEncoding())) {
77 docstring const file = makeDisplayPath(s.absFilename(), 50);
78 docstring text = bformat(_("The specified document\n%1$s"
79 "\ncould not be read."), file);
80 Alert::error(_("Could not read document"), text);
84 // Check if emergency save file exists and is newer.
85 FileName const e(s.absFilename() + ".emergency");
87 if (fs::exists(e.toFilesystemEncoding()) &&
88 fs::exists(s.toFilesystemEncoding()) &&
89 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
91 docstring const file = makeDisplayPath(s.absFilename(), 20);
92 docstring const text =
93 bformat(_("An emergency save of the document "
95 "Recover emergency save?"), file);
96 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
97 _("&Recover"), _("&Load Original"),
101 // the file is not saved if we load the emergency file.
103 return b->readFile(e.absFilename());
111 // Now check if autosave file is newer.
112 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
114 if (fs::exists(a.toFilesystemEncoding()) &&
115 fs::exists(s.toFilesystemEncoding()) &&
116 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
118 docstring const file = makeDisplayPath(s.absFilename(), 20);
119 docstring const text =
120 bformat(_("The backup of the document "
121 "%1$s is newer.\n\nLoad the "
122 "backup instead?"), file);
123 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
124 _("&Load backup"), _("Load &original"),
128 // the file is not saved if we load the autosave file.
130 return b->readFile(a.absFilename());
132 // Here we delete the autosave
139 return b->readFile(s.absFilename());
147 bool loadLyXFile(Buffer * b, FileName const & s)
151 if (fs::is_readable(s.toFilesystemEncoding())) {
152 if (readFile(b, s)) {
153 b->lyxvc().file_found_hook(s);
154 if (!fs::is_writable(s.toFilesystemEncoding()))
155 b->setReadonly(true);
159 docstring const file = makeDisplayPath(s.absFilename(), 20);
160 // Here we probably should run
161 if (LyXVC::file_not_found_hook(s)) {
162 docstring const text =
163 bformat(_("Do you want to retrieve the document"
164 " %1$s from version control?"), file);
165 int const ret = Alert::prompt(_("Retrieve from version control?"),
166 text, 0, 1, _("&Retrieve"), _("&Cancel"));
169 // How can we know _how_ to do the checkout?
170 // With the current VC support it has to be,
171 // a RCS file since CVS do not have special ,v files.
173 return loadLyXFile(b, s);
180 // FIXME newFile() should probably be a member method of Application...
181 Buffer * newFile(string const & filename, string const & templatename,
185 Buffer * b = theBufferList().newBuffer(filename);
189 // use defaults.lyx as a default template if it exists.
190 if (templatename.empty())
191 tname = libFileSearch("templates", "defaults.lyx").absFilename();
193 tname = templatename;
195 if (!tname.empty()) {
196 if (!b->readFile(tname)) {
197 docstring const file = makeDisplayPath(tname, 50);
198 docstring const text = bformat(
199 _("The specified document template\n%1$s\ncould not be read."),
201 Alert::error(_("Could not read template"), text);
202 theBufferList().release(b);
209 b->setFileName(filename);
212 b->setReadonly(false);
213 b->fully_loaded(true);
214 b->updateDocLang(b->params().language);
220 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
221 ErrorList & errorList)
223 TeXErrors::Errors::const_iterator cit = terr.begin();
224 TeXErrors::Errors::const_iterator end = terr.end();
226 for (; cit != end; ++cit) {
229 int errorrow = cit->error_in_line;
230 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
236 found = buf.texrow().getIdFromRow(errorrow, id_end,
238 } while (found && id_start == id_end && pos_start == pos_end);
240 errorList.push_back(ErrorItem(cit->error_desc,
241 cit->error_text, id_start, pos_start, pos_end));
246 string const bufferFormat(Buffer const & buffer)
248 if (buffer.isDocBook())
250 else if (buffer.isLiterate())
257 int countWords(DocIterator const & from, DocIterator const & to)
261 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
262 // Copied and adapted from isLetter() in ControlSpellChecker
264 && dit.pos() != dit.lastpos()
265 && dit.paragraph().isLetter(dit.pos())
266 && !dit.paragraph().isDeleted(dit.pos())) {
281 depth_type getDepth(DocIterator const & it)
283 depth_type depth = 0;
284 for (size_t i = 0 ; i < it.depth() ; ++i)
285 if (!it[i].inset().inMathed())
286 depth += it[i].paragraph().getDepth() + 1;
287 // remove 1 since the outer inset does not count
291 depth_type getItemDepth(ParIterator const & it)
293 Paragraph const & par = *it;
294 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
296 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
299 // this will hold the lowest depth encountered up to now.
300 depth_type min_depth = getDepth(it);
301 ParIterator prev_it = it;
304 --prev_it.top().pit();
306 // start of nested inset: go to outer par
308 if (prev_it.empty()) {
309 // start of document: nothing to do
314 // We search for the first paragraph with same label
315 // that is not more deeply nested.
316 Paragraph & prev_par = *prev_it;
317 depth_type const prev_depth = getDepth(prev_it);
318 if (labeltype == prev_par.layout()->labeltype) {
319 if (prev_depth < min_depth) {
320 return prev_par.itemdepth + 1;
322 else if (prev_depth == min_depth) {
323 return prev_par.itemdepth;
326 min_depth = std::min(min_depth, prev_depth);
327 // small optimization: if we are at depth 0, we won't
328 // find anything else
329 if (prev_depth == 0) {
336 bool needEnumCounterReset(ParIterator const & it)
338 Paragraph const & par = *it;
339 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
340 depth_type const cur_depth = par.getDepth();
341 ParIterator prev_it = it;
342 while (prev_it.pit()) {
343 --prev_it.top().pit();
344 Paragraph const & prev_par = *prev_it;
345 if (prev_par.getDepth() <= cur_depth)
346 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
348 // start of nested inset: reset
353 // set the label of a paragraph. This includes the counters.
354 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
356 Paragraph & par = *it;
357 LyXLayout_ptr const & layout = par.layout();
358 Counters & counters = textclass.counters();
361 par.params().appendix(par.params().startOfAppendix());
363 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
364 if (!par.params().appendix() &&
365 par.params().startOfAppendix()) {
366 par.params().appendix(true);
367 textclass.counters().reset();
371 // Compute the item depth of the paragraph
372 par.itemdepth = getItemDepth(it);
374 // erase what was there before
375 par.params().labelString(docstring());
377 if (layout->margintype == MARGIN_MANUAL) {
378 if (par.params().labelWidthString().empty())
379 par.setLabelWidthString(buf.translateLabel(layout->labelstring()));
381 par.setLabelWidthString(docstring());
384 // is it a layout that has an automatic label?
385 if (layout->labeltype == LABEL_COUNTER) {
386 if (layout->toclevel <= buf.params().secnumdepth
387 && (layout->latextype != LATEX_ENVIRONMENT
388 || isFirstInSequence(it.pit(), it.plist()))) {
389 counters.step(layout->counter);
390 docstring label = expandLabel(buf, layout,
391 par.params().appendix());
392 par.params().labelString(label);
394 } else if (layout->labeltype == LABEL_ITEMIZE) {
395 // At some point of time we should do something more
396 // clever here, like:
397 // par.params().labelString(
398 // buf.params().user_defined_bullet(par.itemdepth).getText());
399 // for now, use a simple hardcoded label
401 switch (par.itemdepth) {
403 itemlabel = char_type(0x2022);
406 itemlabel = char_type(0x2013);
409 itemlabel = char_type(0x2217);
412 itemlabel += char_type(0x2219); // or 0x00b7
416 par.params().labelString(itemlabel);
417 } else if (layout->labeltype == LABEL_ENUMERATE) {
419 // Yes I know this is a really, really! bad solution
421 docstring enumcounter = from_ascii("enum");
423 switch (par.itemdepth) {
435 // not a valid enumdepth...
439 // Maybe we have to reset the enumeration counter.
440 if (needEnumCounterReset(it))
441 counters.reset(enumcounter);
443 counters.step(enumcounter);
447 switch (par.itemdepth) {
449 format = N_("\\arabic{enumi}.");
452 format = N_("(\\alph{enumii})");
455 format = N_("\\roman{enumiii}.");
458 format = N_("\\Alph{enumiv}.");
461 // not a valid enumdepth...
465 par.params().labelString(counters.counterLabel(buf.B_(format)));
466 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
467 counters.step(from_ascii("bibitem"));
468 int number = counters.value(from_ascii("bibitem"));
470 par.bibitem()->setCounter(number);
471 par.params().labelString(buf.translateLabel(layout->labelstring()));
472 // In biblio should't be following counters but...
473 } else if (layout->labeltype == LABEL_SENSITIVE) {
474 // Search for the first float or wrap inset in the iterator
476 size_t i = it.depth();
479 InsetBase * const in = &it[i].inset();
480 if (in->lyxCode() == InsetBase::FLOAT_CODE
481 || in->lyxCode() == InsetBase::WRAP_CODE) {
482 type = in->getInsetName();
489 Floating const & fl = textclass.floats().getType(to_ascii(type));
491 counters.step(from_ascii(fl.type()));
493 // Doesn't work... yet.
494 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
496 // par->SetLayout(0);
497 s = buf.translateLabel(layout->labelstring());
500 par.params().labelString(s);
501 } else if (layout->labeltype == LABEL_NO_LABEL)
502 par.params().labelString(docstring());
504 par.params().labelString(buf.translateLabel(layout->labelstring()));
510 bool updateCurrentLabel(Buffer const & buf,
513 if (it == par_iterator_end(buf.inset()))
516 // if (it.lastpit == 0 && LyXText::isMainText(buf))
519 switch (it->layout()->labeltype) {
524 case LABEL_TOP_ENVIRONMENT:
525 case LABEL_CENTERED_TOP_ENVIRONMENT:
528 setLabel(buf, it, buf.params().getLyXTextClass());
531 case LABEL_SENSITIVE:
533 // do more things with enumerate later
534 case LABEL_ENUMERATE:
538 // This is dead code which get rid of a warning:
543 void updateLabels(Buffer const & buf,
544 ParIterator & from, ParIterator & to, bool childonly)
546 for (ParIterator it = from; it != to; ++it) {
547 if (it.pit() > it.lastpit())
549 if (!updateCurrentLabel (buf, it)) {
550 updateLabels(buf, childonly);
557 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
559 if (updateCurrentLabel(buf, iter))
562 updateLabels(buf, childonly);
566 void updateLabels(Buffer const & buf, bool childonly)
568 // Use the master text class also for child documents
569 LyXTextClass const & textclass = buf.params().getLyXTextClass();
572 // If this is a child document start with the master
573 Buffer const * const master = buf.getMasterBuffer();
574 if (master != &buf) {
575 updateLabels(*master);
579 // start over the counters
580 textclass.counters().reset();
583 ParIterator const end = par_iterator_end(buf.inset());
585 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
586 // reduce depth if necessary
588 Paragraph const & prevpar = it.plist()[it.pit() - 1];
589 it->params().depth(min(it->params().depth(),
590 prevpar.getMaxDepthAfter()));
592 it->params().depth(0);
594 // set the counter for this paragraph
595 setLabel(buf, it, textclass);
598 InsetList::const_iterator iit = it->insetlist.begin();
599 InsetList::const_iterator end = it->insetlist.end();
600 for (; iit != end; ++iit) {
601 if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
602 static_cast<InsetInclude const *>(iit->inset)
607 const_cast<Buffer &>(buf).tocBackend().update();
611 docstring expandLabel(Buffer const & buf,
612 LyXLayout_ptr const & layout, bool appendix)
614 LyXTextClass const & tclass = buf.params().getLyXTextClass();
616 docstring fmt = buf.translateLabel(appendix ?
617 layout->labelstring_appendix() :
618 layout->labelstring());
620 // handle 'inherited level parts' in 'fmt',
621 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
622 size_t const i = fmt.find('@', 0);
623 if (i != docstring::npos) {
624 size_t const j = fmt.find('@', i + 1);
625 if (j != docstring::npos) {
626 docstring parent(fmt, i + 1, j - i - 1);
628 docstring label = expandLabel(buf, tclass[to_utf8(parent)], appendix);
629 fmt = docstring(fmt, 0, i) + label + docstring(fmt, j + 1, docstring::npos);
633 return tclass.counters().counterLabel(fmt);