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 "vc-backend.h"
38 #include "frontends/Alert.h"
40 #include "insets/insetbibitem.h"
42 #include "support/filetools.h"
43 #include "support/fs_extras.h"
44 #include "support/lyxlib.h"
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.hpp>
54 using lyx::support::bformat;
55 using lyx::support::libFileSearch;
56 using lyx::support::makeDisplayPath;
57 using lyx::support::onlyFilename;
58 using lyx::support::onlyPath;
59 using lyx::support::unlink;
64 namespace fs = boost::filesystem;
66 extern BufferList bufferlist;
70 bool readFile(Buffer * const b, string const & s)
74 // File information about normal file
76 string const file = makeDisplayPath(s, 50);
77 string text = bformat(_("The specified document\n%1$s"
78 "\ncould not be read."), file);
79 Alert::error(_("Could not read document"), text);
83 // Check if emergency save file exists and is newer.
84 string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
86 if (fs::exists(e) && fs::exists(s)
87 && fs::last_write_time(e) > fs::last_write_time(s))
89 string const file = makeDisplayPath(s, 20);
91 bformat(_("An emergency save of the document "
93 "Recover emergency save?"), file);
94 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
95 _("&Recover"), _("&Load Original"),
99 // the file is not saved if we load the emergency file.
101 return b->readFile(e);
109 // Now check if autosave file is newer.
110 string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
112 if (fs::exists(a) && fs::exists(s)
113 && fs::last_write_time(a) > fs::last_write_time(s))
115 string const file = makeDisplayPath(s, 20);
117 bformat(_("The backup of the document "
118 "%1$s is newer.\n\nLoad the "
119 "backup instead?"), file);
120 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
121 _("&Load backup"), _("Load &original"),
125 // the file is not saved if we load the autosave file.
127 return b->readFile(a);
129 // Here we delete the autosave
136 return b->readFile(s);
144 bool loadLyXFile(Buffer * b, string const & s)
148 if (fs::is_readable(s)) {
149 if (readFile(b, s)) {
150 b->lyxvc().file_found_hook(s);
151 if (!fs::is_writable(s))
152 b->setReadonly(true);
156 string const file = makeDisplayPath(s, 20);
157 // Here we probably should run
158 if (LyXVC::file_not_found_hook(s)) {
160 bformat(_("Do you want to retrieve the document"
161 " %1$s from version control?"), file);
162 int const ret = Alert::prompt(_("Retrieve from version control?"),
163 text, 0, 1, _("&Retrieve"), _("&Cancel"));
166 // How can we know _how_ to do the checkout?
167 // With the current VC support it has to be,
168 // a RCS file since CVS do not have special ,v files.
170 return loadLyXFile(b, s);
178 Buffer * newFile(string const & filename, string const & templatename,
182 Buffer * b = bufferlist.newBuffer(filename);
186 // use defaults.lyx as a default template if it exists.
187 if (templatename.empty())
188 tname = libFileSearch("templates", "defaults.lyx");
190 tname = templatename;
192 if (!tname.empty()) {
193 if (!b->readFile(tname)) {
194 string const file = makeDisplayPath(tname, 50);
195 string const text = bformat(_("The specified document template\n%1$s\ncould not be read."), file);
196 Alert::error(_("Could not read template"), text);
197 bufferlist.release(b);
204 b->setFileName(filename);
207 b->setReadonly(false);
208 b->fully_loaded(true);
209 b->updateDocLang(b->params().language);
215 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
216 ErrorList & errorList)
218 TeXErrors::Errors::const_iterator cit = terr.begin();
219 TeXErrors::Errors::const_iterator end = terr.end();
221 for (; cit != end; ++cit) {
224 int errorrow = cit->error_in_line;
225 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
231 found = buf.texrow().getIdFromRow(errorrow, id_end,
233 } while (found && id_start == id_end && pos_start == pos_end);
235 errorList.push_back(ErrorItem(cit->error_desc,
236 cit->error_text, id_start, pos_start, pos_end));
241 string const bufferFormat(Buffer const & buffer)
243 if (buffer.isDocBook())
245 else if (buffer.isLiterate())
252 int countWords(DocIterator const & from, DocIterator const & to)
256 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
257 // Copied and adapted from isLetter() in ControlSpellChecker
259 && dit.pos() != dit.lastpos()
260 && dit.paragraph().isLetter(dit.pos())
261 && !isDeletedText(dit.paragraph(), dit.pos())) {
276 lyx::depth_type getDepth(DocIterator const & it)
278 lyx::depth_type depth = 0;
279 for (size_t i = 0 ; i < it.depth() ; ++i)
280 if (!it[i].inset().inMathed())
281 depth += it[i].paragraph().getDepth() + 1;
282 // remove 1 since the outer inset does not count
286 lyx::depth_type getItemDepth(ParIterator const & it)
288 Paragraph const & par = *it;
289 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
291 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
294 // this will hold the lowest depth encountered up to now.
295 lyx::depth_type min_depth = getDepth(it);
296 ParIterator prev_it = it;
299 --prev_it.top().pit();
301 // start of nested inset: go to outer par
303 if (prev_it.empty()) {
304 // start of document: nothing to do
309 // We search for the first paragraph with same label
310 // that is not more deeply nested.
311 Paragraph & prev_par = *prev_it;
312 lyx::depth_type const prev_depth = getDepth(prev_it);
313 if (labeltype == prev_par.layout()->labeltype) {
314 if (prev_depth < min_depth) {
315 return prev_par.itemdepth + 1;
317 else if (prev_depth == min_depth) {
318 return prev_par.itemdepth;
321 min_depth = std::min(min_depth, prev_depth);
322 // small optimization: if we are at depth 0, we won't
323 // find anything else
324 if (prev_depth == 0) {
331 bool needEnumCounterReset(ParIterator const & it)
333 Paragraph const & par = *it;
334 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
335 lyx::depth_type const cur_depth = par.getDepth();
336 ParIterator prev_it = it;
337 while (prev_it.pit()) {
338 --prev_it.top().pit();
339 Paragraph const & prev_par = *prev_it;
340 if (prev_par.getDepth() <= cur_depth)
341 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
343 // start of nested inset: reset
348 // set the label of a paragraph. This includes the counters.
349 void setLabel(Buffer const & buf, ParIterator & it)
351 Paragraph & par = *it;
352 BufferParams const & bufparams = buf.params();
353 LyXTextClass const & textclass = bufparams.getLyXTextClass();
354 LyXLayout_ptr const & layout = par.layout();
355 Counters & counters = textclass.counters();
358 par.params().appendix(par.params().startOfAppendix());
360 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
361 if (!par.params().appendix() &&
362 par.params().startOfAppendix()) {
363 par.params().appendix(true);
364 textclass.counters().reset();
368 // Compute the item depth of the paragraph
369 par.itemdepth = getItemDepth(it);
371 // erase what was there before
372 par.params().labelString(string());
374 if (layout->margintype == MARGIN_MANUAL) {
375 if (par.params().labelWidthString().empty())
376 par.setLabelWidthString(layout->labelstring());
378 par.setLabelWidthString(string());
381 // is it a layout that has an automatic label?
382 if (layout->labeltype == LABEL_COUNTER) {
383 if (layout->toclevel <= buf.params().secnumdepth
384 && (layout->latextype != LATEX_ENVIRONMENT
385 || isFirstInSequence(it.pit(), it.plist()))) {
386 counters.step(layout->counter);
387 string label = expandLabel(buf, layout,
388 par.params().appendix());
389 par.params().labelString(label);
391 } else if (layout->labeltype == LABEL_ITEMIZE) {
392 // At some point of time we should do something more
393 // clever here, like:
394 // par.params().labelString(
395 // bufparams.user_defined_bullet(par.itemdepth).getText());
396 // for now, use a simple hardcoded label
398 switch (par.itemdepth) {
413 par.params().labelString(itemlabel);
414 } else if (layout->labeltype == LABEL_ENUMERATE) {
416 // Yes I know this is a really, really! bad solution
418 string enumcounter = "enum";
420 switch (par.itemdepth) {
432 // not a valid enumdepth...
436 // Maybe we have to reset the enumeration counter.
437 if (needEnumCounterReset(it))
438 counters.reset(enumcounter);
440 counters.step(enumcounter);
444 switch (par.itemdepth) {
446 format = N_("\\arabic{enumi}.");
449 format = N_("(\\alph{enumii})");
452 format = N_("\\roman{enumiii}.");
455 format = N_("\\Alph{enumiv}.");
458 // not a valid enumdepth...
462 par.params().labelString(counters.counterLabel(buf.B_(format)));
463 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
464 counters.step("bibitem");
465 int number = counters.value("bibitem");
467 par.bibitem()->setCounter(number);
468 par.params().labelString(buf.B_(layout->labelstring()));
469 // In biblio should't be following counters but...
470 } else if (layout->labeltype == LABEL_SENSITIVE) {
471 // Search for the first float or wrap inset in the iterator
473 size_t i = it.depth();
476 InsetBase * const in = &it[i].inset();
477 if (in->lyxCode() == InsetBase::FLOAT_CODE
478 || in->lyxCode() == InsetBase::WRAP_CODE) {
479 type = in->getInsetName();
486 Floating const & fl = textclass.floats().getType(type);
488 counters.step(fl.type());
490 // Doesn't work... yet.
491 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
493 // par->SetLayout(0);
494 s = buf.B_(layout->labelstring());
497 par.params().labelString(s);
498 } else if (layout->labeltype == LABEL_NO_LABEL)
499 par.params().labelString(string());
501 par.params().labelString(buf.B_(layout->labelstring()));
507 bool updateCurrentLabel(Buffer const & buf,
510 if (it == par_iterator_end(buf.inset()))
513 // if (it.lastpit == 0 && LyXText::isMainText())
516 switch (it->layout()->labeltype) {
521 case LABEL_TOP_ENVIRONMENT:
522 case LABEL_CENTERED_TOP_ENVIRONMENT:
528 case LABEL_SENSITIVE:
530 // do more things with enumerate later
531 case LABEL_ENUMERATE:
535 // This is dead code which get rid of a warning:
540 void updateLabels(Buffer const & buf,
541 ParIterator & from, ParIterator & to)
543 for (ParIterator it = from; it != to; ++it) {
544 if (it.pit() > it.lastpit())
546 if (!updateCurrentLabel (buf, it)) {
554 void updateLabels(Buffer const & buf,
557 if (updateCurrentLabel(buf, iter))
564 void updateLabels(Buffer const & buf)
566 // start over the counters
567 buf.params().getLyXTextClass().counters().reset();
569 ParIterator const end = par_iterator_end(buf.inset());
571 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
572 // reduce depth if necessary
574 Paragraph const & prevpar = it.plist()[it.pit() - 1];
575 it->params().depth(min(it->params().depth(),
576 prevpar.getMaxDepthAfter()));
578 it->params().depth(0);
580 // set the counter for this paragraph
584 lyx::toc::updateToc(buf);
588 string expandLabel(Buffer const & buf,
589 LyXLayout_ptr const & layout, bool appendix)
591 LyXTextClass const & tclass = buf.params().getLyXTextClass();
593 string fmt = buf.B_(appendix ? layout->labelstring_appendix()
594 : layout->labelstring());
596 // handle 'inherited level parts' in 'fmt',
597 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
598 size_t const i = fmt.find('@', 0);
599 if (i != string::npos) {
600 size_t const j = fmt.find('@', i + 1);
601 if (j != string::npos) {
602 string parent(fmt, i + 1, j - i - 1);
603 string label = expandLabel(buf, tclass[parent], appendix);
604 fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
608 return tclass.counters().counterLabel(fmt);