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 Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "paragraph_funcs.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetText.h"
75 #include "mathed/MacroTable.h"
76 #include "mathed/MathMacroTemplate.h"
77 #include "mathed/MathSupport.h"
79 #include "frontends/alert.h"
80 #include "frontends/Delegates.h"
81 #include "frontends/WorkAreaManager.h"
83 #include "graphics/Previews.h"
85 #include "support/lassert.h"
86 #include "support/convert.h"
87 #include "support/debug.h"
88 #include "support/docstring_list.h"
89 #include "support/ExceptionMessage.h"
90 #include "support/FileName.h"
91 #include "support/FileNameList.h"
92 #include "support/filetools.h"
93 #include "support/ForkedCalls.h"
94 #include "support/gettext.h"
95 #include "support/gzstream.h"
96 #include "support/lstrings.h"
97 #include "support/lyxalgo.h"
98 #include "support/os.h"
99 #include "support/Package.h"
100 #include "support/Path.h"
101 #include "support/Systemcall.h"
102 #include "support/textutils.h"
103 #include "support/types.h"
105 #include <boost/bind.hpp>
106 #include <boost/shared_ptr.hpp>
118 using namespace lyx::support;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
127 // Do not remove the comment below, so we get merge conflict in
128 // independent branches. Instead add your own.
129 int const LYX_FORMAT = 361; // jspitzm: bibliography custom width
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
144 class BufferSet : public std::set<Buffer const *> {};
149 Impl(Buffer & parent, FileName const & file, bool readonly);
163 mutable TexRow texrow;
165 /// need to regenerate .tex?
169 mutable bool lyx_clean;
171 /// is autosave needed?
172 mutable bool bak_clean;
174 /// is this a unnamed file (New...)?
180 /// name of the file the buffer is associated with.
183 /** Set to true only when the file is fully loaded.
184 * Used to prevent the premature generation of previews
185 * and by the citation inset.
187 bool file_fully_loaded;
190 mutable TocBackend toc_backend;
193 typedef pair<DocIterator, MacroData> ScopeMacro;
194 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
195 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
196 /// map from the macro name to the position map,
197 /// which maps the macro definition position to the scope and the MacroData.
198 NamePositionScopeMacroMap macros;
201 /// positions of child buffers in the buffer
202 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
203 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
204 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
205 /// position of children buffers in this buffer
206 BufferPositionMap children_positions;
207 /// map from children inclusion positions to their scope and their buffer
208 PositionScopeBufferMap position_to_children;
210 /// Container for all sort of Buffer dependant errors.
211 map<string, ErrorList> errorLists;
213 /// timestamp and checksum used to test if the file has been externally
214 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
216 unsigned long checksum_;
219 frontend::WorkAreaManager * wa_;
224 /// A cache for the bibfiles (including bibfiles of loaded child
225 /// documents), needed for appropriate update of natbib labels.
226 mutable support::FileNameList bibfilesCache_;
228 // FIXME The caching mechanism could be improved. At present, we have a
229 // cache for each Buffer, that caches all the bibliography info for that
230 // Buffer. A more efficient solution would be to have a global cache per
231 // file, and then to construct the Buffer's bibinfo from that.
232 /// A cache for bibliography info
233 mutable BiblioInfo bibinfo_;
234 /// whether the bibinfo cache is valid
235 bool bibinfoCacheValid_;
236 /// Cache of timestamps of .bib files
237 map<FileName, time_t> bibfileStatus_;
239 mutable RefCache ref_cache_;
241 /// our Text that should be wrapped in an InsetText
244 /// This is here to force the test to be done whenever parent_buffer
246 Buffer const * parent() const {
247 // if parent_buffer is not loaded, then it has been unloaded,
248 // which means that parent_buffer is an invalid pointer. So we
249 // set it to null in that case.
250 if (!theBufferList().isLoaded(parent_buffer))
252 return parent_buffer;
255 void setParent(Buffer const * pb) { parent_buffer = pb; }
257 /// So we can force access via the accessors.
258 mutable Buffer const * parent_buffer;
262 /// Creates the per buffer temporary directory
263 static FileName createBufferTmpDir()
266 // We are in our own directory. Why bother to mangle name?
267 // In fact I wrote this code to circumvent a problematic behaviour
268 // (bug?) of EMX mkstemp().
269 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
270 convert<string>(count++));
272 if (!tmpfl.createDirectory(0777)) {
273 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
274 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
275 from_utf8(tmpfl.absFilename())));
281 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
282 : lyx_clean(true), bak_clean(true), unnamed(false),
283 read_only(readonly_), filename(file), file_fully_loaded(false),
284 toc_backend(&parent), macro_lock(false), timestamp_(0),
285 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
288 temppath = createBufferTmpDir();
289 lyxvc.setBuffer(&parent);
291 wa_ = new frontend::WorkAreaManager;
295 Buffer::Buffer(string const & file, bool readonly)
296 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
298 LYXERR(Debug::INFO, "Buffer::Buffer()");
300 d->inset = new InsetText(*this);
301 d->inset->setAutoBreakRows(true);
302 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
308 LYXERR(Debug::INFO, "Buffer::~Buffer()");
309 // here the buffer should take care that it is
310 // saved properly, before it goes into the void.
312 // GuiView already destroyed
315 if (d->unnamed && d->filename.extension() == "internal") {
316 // No need to do additional cleanups for internal buffer.
321 // loop over children
322 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
323 Impl::BufferPositionMap::iterator end = d->children_positions.end();
324 for (; it != end; ++it) {
325 Buffer * child = const_cast<Buffer *>(it->first);
326 // The child buffer might have been closed already.
327 if (theBufferList().isLoaded(child))
328 theBufferList().releaseChild(this, child);
331 // clear references to children in macro tables
332 d->children_positions.clear();
333 d->position_to_children.clear();
335 if (!d->temppath.destroyDirectory()) {
336 Alert::warning(_("Could not remove temporary directory"),
337 bformat(_("Could not remove the temporary directory %1$s"),
338 from_utf8(d->temppath.absFilename())));
341 // Remove any previewed LaTeX snippets associated with this buffer.
342 thePreviews().removeLoader(*this);
348 void Buffer::changed() const
355 frontend::WorkAreaManager & Buffer::workAreaManager() const
357 LASSERT(d->wa_, /**/);
362 Text & Buffer::text() const
364 return d->inset->text();
368 Inset & Buffer::inset() const
374 BufferParams & Buffer::params()
380 BufferParams const & Buffer::params() const
386 ParagraphList & Buffer::paragraphs()
388 return text().paragraphs();
392 ParagraphList const & Buffer::paragraphs() const
394 return text().paragraphs();
398 LyXVC & Buffer::lyxvc()
404 LyXVC const & Buffer::lyxvc() const
410 string const Buffer::temppath() const
412 return d->temppath.absFilename();
416 TexRow & Buffer::texrow()
422 TexRow const & Buffer::texrow() const
428 TocBackend & Buffer::tocBackend() const
430 return d->toc_backend;
434 Undo & Buffer::undo()
440 string Buffer::latexName(bool const no_path) const
442 FileName latex_name = makeLatexName(d->filename);
443 return no_path ? latex_name.onlyFileName()
444 : latex_name.absFilename();
448 string Buffer::logName(LogType * type) const
450 string const filename = latexName(false);
452 if (filename.empty()) {
458 string const path = temppath();
460 FileName const fname(addName(temppath(),
461 onlyFilename(changeExtension(filename,
464 // FIXME: how do we know this is the name of the build log?
465 FileName const bname(
466 addName(path, onlyFilename(
467 changeExtension(filename,
468 formats.extension(bufferFormat()) + ".out"))));
470 // If no Latex log or Build log is newer, show Build log
472 if (bname.exists() &&
473 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
474 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
477 return bname.absFilename();
479 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
482 return fname.absFilename();
486 void Buffer::setReadonly(bool const flag)
488 if (d->read_only != flag) {
495 void Buffer::setFileName(string const & newfile)
497 d->filename = makeAbsPath(newfile);
498 setReadonly(d->filename.isReadOnly());
503 int Buffer::readHeader(Lexer & lex)
505 int unknown_tokens = 0;
507 int begin_header_line = -1;
509 // Initialize parameters that may be/go lacking in header:
510 params().branchlist().clear();
511 params().preamble.erase();
512 params().options.erase();
513 params().master.erase();
514 params().float_placement.erase();
515 params().paperwidth.erase();
516 params().paperheight.erase();
517 params().leftmargin.erase();
518 params().rightmargin.erase();
519 params().topmargin.erase();
520 params().bottommargin.erase();
521 params().headheight.erase();
522 params().headsep.erase();
523 params().footskip.erase();
524 params().columnsep.erase();
525 params().fontsCJK.erase();
526 params().listings_params.clear();
527 params().clearLayoutModules();
528 params().clearRemovedModules();
529 params().pdfoptions().clear();
530 params().indiceslist().clear();
531 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
533 for (int i = 0; i < 4; ++i) {
534 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
535 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
538 ErrorList & errorList = d->errorLists["Parse"];
547 if (token == "\\end_header")
551 if (token == "\\begin_header") {
552 begin_header_line = line;
556 LYXERR(Debug::PARSER, "Handling document header token: `"
559 string unknown = params().readToken(lex, token, d->filename.onlyPath());
560 if (!unknown.empty()) {
561 if (unknown[0] != '\\' && token == "\\textclass") {
562 Alert::warning(_("Unknown document class"),
563 bformat(_("Using the default document class, because the "
564 "class %1$s is unknown."), from_utf8(unknown)));
567 docstring const s = bformat(_("Unknown token: "
571 errorList.push_back(ErrorItem(_("Document header error"),
576 if (begin_header_line) {
577 docstring const s = _("\\begin_header is missing");
578 errorList.push_back(ErrorItem(_("Document header error"),
582 params().makeDocumentClass();
584 return unknown_tokens;
589 // changed to be public and have one parameter
590 // Returns true if "\end_document" is not read (Asger)
591 bool Buffer::readDocument(Lexer & lex)
593 ErrorList & errorList = d->errorLists["Parse"];
596 if (!lex.checkFor("\\begin_document")) {
597 docstring const s = _("\\begin_document is missing");
598 errorList.push_back(ErrorItem(_("Document header error"),
602 // we are reading in a brand new document
603 LASSERT(paragraphs().empty(), /**/);
607 if (params().outputChanges) {
608 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
609 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
610 LaTeXFeatures::isAvailable("xcolor");
612 if (!dvipost && !xcolorulem) {
613 Alert::warning(_("Changes not shown in LaTeX output"),
614 _("Changes will not be highlighted in LaTeX output, "
615 "because neither dvipost nor xcolor/ulem are installed.\n"
616 "Please install these packages or redefine "
617 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
618 } else if (!xcolorulem) {
619 Alert::warning(_("Changes not shown in LaTeX output"),
620 _("Changes will not be highlighted in LaTeX output "
621 "when using pdflatex, because xcolor and ulem are not installed.\n"
622 "Please install both packages or redefine "
623 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
627 if (!params().master.empty()) {
628 FileName const master_file = makeAbsPath(params().master,
629 onlyPath(absFileName()));
630 if (isLyXFilename(master_file.absFilename())) {
632 checkAndLoadLyXFile(master_file, true);
634 // necessary e.g. after a reload
635 // to re-register the child (bug 5873)
636 // FIXME: clean up updateMacros (here, only
637 // child registering is needed).
638 master->updateMacros();
639 // set master as master buffer, but only
640 // if we are a real child
641 if (master->isChild(this))
643 // if the master is not fully loaded
644 // it is probably just loading this
645 // child. No warning needed then.
646 else if (master->isFullyLoaded())
647 LYXERR0("The master '"
649 << "' assigned to this document ("
651 << ") does not include "
652 "this document. Ignoring the master assignment.");
658 bool const res = text().read(*this, lex, errorList, d->inset);
661 updateMacroInstances();
666 // needed to insert the selection
667 void Buffer::insertStringAsLines(ParagraphList & pars,
668 pit_type & pit, pos_type & pos,
669 Font const & fn, docstring const & str, bool autobreakrows)
673 // insert the string, don't insert doublespace
674 bool space_inserted = true;
675 for (docstring::const_iterator cit = str.begin();
676 cit != str.end(); ++cit) {
677 Paragraph & par = pars[pit];
679 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
680 breakParagraph(params(), pars, pit, pos,
681 par.layout().isEnvironment());
684 space_inserted = true;
688 // do not insert consecutive spaces if !free_spacing
689 } else if ((*cit == ' ' || *cit == '\t') &&
690 space_inserted && !par.isFreeSpacing()) {
692 } else if (*cit == '\t') {
693 if (!par.isFreeSpacing()) {
694 // tabs are like spaces here
695 par.insertChar(pos, ' ', font, params().trackChanges);
697 space_inserted = true;
699 par.insertChar(pos, *cit, font, params().trackChanges);
701 space_inserted = true;
703 } else if (!isPrintable(*cit)) {
704 // Ignore unprintables
707 // just insert the character
708 par.insertChar(pos, *cit, font, params().trackChanges);
710 space_inserted = (*cit == ' ');
717 bool Buffer::readString(string const & s)
719 params().compressed = false;
721 // remove dummy empty par
722 paragraphs().clear();
726 FileName const name = FileName::tempName("Buffer_readString");
727 switch (readFile(lex, name, true)) {
731 // We need to call lyx2lyx, so write the input to a file
732 ofstream os(name.toFilesystemEncoding().c_str());
735 return readFile(name);
745 bool Buffer::readFile(FileName const & filename)
747 FileName fname(filename);
749 params().compressed = fname.isZippedFile();
751 // remove dummy empty par
752 paragraphs().clear();
755 if (readFile(lex, fname) != success)
762 bool Buffer::isFullyLoaded() const
764 return d->file_fully_loaded;
768 void Buffer::setFullyLoaded(bool value)
770 d->file_fully_loaded = value;
774 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
777 LASSERT(!filename.empty(), /**/);
779 // the first (non-comment) token _must_ be...
780 if (!lex.checkFor("\\lyxformat")) {
781 Alert::error(_("Document format failure"),
782 bformat(_("%1$s is not a readable LyX document."),
783 from_utf8(filename.absFilename())));
789 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
790 // if present remove ".," from string.
791 size_t dot = tmp_format.find_first_of(".,");
792 //lyxerr << " dot found at " << dot << endl;
793 if (dot != string::npos)
794 tmp_format.erase(dot, 1);
795 int const file_format = convert<int>(tmp_format);
796 //lyxerr << "format: " << file_format << endl;
798 // save timestamp and checksum of the original disk file, making sure
799 // to not overwrite them with those of the file created in the tempdir
800 // when it has to be converted to the current format.
802 // Save the timestamp and checksum of disk file. If filename is an
803 // emergency file, save the timestamp and checksum of the original lyx file
804 // because isExternallyModified will check for this file. (BUG4193)
805 string diskfile = filename.absFilename();
806 if (suffixIs(diskfile, ".emergency"))
807 diskfile = diskfile.substr(0, diskfile.size() - 10);
808 saveCheckSum(FileName(diskfile));
811 if (file_format != LYX_FORMAT) {
814 // lyx2lyx would fail
817 FileName const tmpfile = FileName::tempName("Buffer_readFile");
818 if (tmpfile.empty()) {
819 Alert::error(_("Conversion failed"),
820 bformat(_("%1$s is from a different"
821 " version of LyX, but a temporary"
822 " file for converting it could"
824 from_utf8(filename.absFilename())));
827 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
828 if (lyx2lyx.empty()) {
829 Alert::error(_("Conversion script not found"),
830 bformat(_("%1$s is from a different"
831 " version of LyX, but the"
832 " conversion script lyx2lyx"
833 " could not be found."),
834 from_utf8(filename.absFilename())));
837 ostringstream command;
838 command << os::python()
839 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
840 << " -t " << convert<string>(LYX_FORMAT)
841 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
842 << ' ' << quoteName(filename.toFilesystemEncoding());
843 string const command_str = command.str();
845 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
847 cmd_ret const ret = runCommand(command_str);
848 if (ret.first != 0) {
849 Alert::error(_("Conversion script failed"),
850 bformat(_("%1$s is from a different version"
851 " of LyX, but the lyx2lyx script"
852 " failed to convert it."),
853 from_utf8(filename.absFilename())));
856 bool const ret = readFile(tmpfile);
857 // Do stuff with tmpfile name and buffer name here.
858 return ret ? success : failure;
863 if (readDocument(lex)) {
864 Alert::error(_("Document format failure"),
865 bformat(_("%1$s ended unexpectedly, which means"
866 " that it is probably corrupted."),
867 from_utf8(filename.absFilename())));
870 d->file_fully_loaded = true;
875 // Should probably be moved to somewhere else: BufferView? LyXView?
876 bool Buffer::save() const
878 // We don't need autosaves in the immediate future. (Asger)
879 resetAutosaveTimers();
881 string const encodedFilename = d->filename.toFilesystemEncoding();
884 bool madeBackup = false;
886 // make a backup if the file already exists
887 if (lyxrc.make_backup && fileName().exists()) {
888 backupName = FileName(absFileName() + '~');
889 if (!lyxrc.backupdir_path.empty()) {
890 string const mangledName =
891 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
892 backupName = FileName(addName(lyxrc.backupdir_path,
895 if (fileName().copyTo(backupName)) {
898 Alert::error(_("Backup failure"),
899 bformat(_("Cannot create backup file %1$s.\n"
900 "Please check whether the directory exists and is writeable."),
901 from_utf8(backupName.absFilename())));
902 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
906 // ask if the disk file has been externally modified (use checksum method)
907 if (fileName().exists() && isExternallyModified(checksum_method)) {
908 docstring const file = makeDisplayPath(absFileName(), 20);
909 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
910 "you want to overwrite this file?"), file);
911 int const ret = Alert::prompt(_("Overwrite modified file?"),
912 text, 1, 1, _("&Overwrite"), _("&Cancel"));
917 if (writeFile(d->filename)) {
921 // Saving failed, so backup is not backup
923 backupName.moveTo(d->filename);
929 bool Buffer::writeFile(FileName const & fname) const
931 if (d->read_only && fname == d->filename)
936 docstring const str = bformat(_("Saving document %1$s..."),
937 makeDisplayPath(fname.absFilename()));
940 if (params().compressed) {
941 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
942 retval = ofs && write(ofs);
944 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
945 retval = ofs && write(ofs);
949 message(str + _(" could not write file!"));
953 removeAutosaveFile();
955 saveCheckSum(d->filename);
956 message(str + _(" done."));
962 bool Buffer::write(ostream & ofs) const
965 // Use the standard "C" locale for file output.
966 ofs.imbue(locale::classic());
969 // The top of the file should not be written by params().
971 // write out a comment in the top of the file
972 ofs << "#LyX " << lyx_version
973 << " created this file. For more info see http://www.lyx.org/\n"
974 << "\\lyxformat " << LYX_FORMAT << "\n"
975 << "\\begin_document\n";
977 /// For each author, set 'used' to true if there is a change
978 /// by this author in the document; otherwise set it to 'false'.
979 AuthorList::Authors::const_iterator a_it = params().authors().begin();
980 AuthorList::Authors::const_iterator a_end = params().authors().end();
981 for (; a_it != a_end; ++a_it)
982 a_it->second.setUsed(false);
984 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
985 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
986 for ( ; it != end; ++it)
987 it->checkAuthors(params().authors());
989 // now write out the buffer parameters.
990 ofs << "\\begin_header\n";
991 params().writeFile(ofs);
992 ofs << "\\end_header\n";
995 ofs << "\n\\begin_body\n";
996 text().write(*this, ofs);
997 ofs << "\n\\end_body\n";
999 // Write marker that shows file is complete
1000 ofs << "\\end_document" << endl;
1002 // Shouldn't really be needed....
1005 // how to check if close went ok?
1006 // Following is an attempt... (BE 20001011)
1008 // good() returns false if any error occured, including some
1009 // formatting error.
1010 // bad() returns true if something bad happened in the buffer,
1011 // which should include file system full errors.
1016 lyxerr << "File was not closed properly." << endl;
1023 bool Buffer::makeLaTeXFile(FileName const & fname,
1024 string const & original_path,
1025 OutputParams const & runparams_in,
1026 bool output_preamble, bool output_body) const
1028 OutputParams runparams = runparams_in;
1029 if (params().useXetex)
1030 runparams.flavor = OutputParams::XETEX;
1032 string const encoding = runparams.encoding->iconvName();
1033 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1036 try { ofs.reset(encoding); }
1037 catch (iconv_codecvt_facet_exception & e) {
1038 lyxerr << "Caught iconv exception: " << e.what() << endl;
1039 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1040 "verify that the support software for your encoding (%1$s) is "
1041 "properly installed"), from_ascii(encoding)));
1044 if (!openFileWrite(ofs, fname))
1047 //TexStream ts(ofs.rdbuf(), &texrow());
1048 ErrorList & errorList = d->errorLists["Export"];
1050 bool failed_export = false;
1053 writeLaTeXSource(ofs, original_path,
1054 runparams, output_preamble, output_body);
1056 catch (EncodingException & e) {
1057 odocstringstream ods;
1058 ods.put(e.failed_char);
1060 oss << "0x" << hex << e.failed_char << dec;
1061 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1062 " (code point %2$s)"),
1063 ods.str(), from_utf8(oss.str()));
1064 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1065 "representable in the chosen encoding.\n"
1066 "Changing the document encoding to utf8 could help."),
1067 e.par_id, e.pos, e.pos + 1));
1068 failed_export = true;
1070 catch (iconv_codecvt_facet_exception & e) {
1071 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1072 _(e.what()), -1, 0, 0));
1073 failed_export = true;
1075 catch (exception const & e) {
1076 errorList.push_back(ErrorItem(_("conversion failed"),
1077 _(e.what()), -1, 0, 0));
1078 failed_export = true;
1081 lyxerr << "Caught some really weird exception..." << endl;
1087 failed_export = true;
1088 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1092 return !failed_export;
1096 void Buffer::writeLaTeXSource(odocstream & os,
1097 string const & original_path,
1098 OutputParams const & runparams_in,
1099 bool const output_preamble, bool const output_body) const
1101 // The child documents, if any, shall be already loaded at this point.
1103 OutputParams runparams = runparams_in;
1105 // Classify the unicode characters appearing in math insets
1106 Encodings::initUnicodeMath(*this);
1108 // validate the buffer.
1109 LYXERR(Debug::LATEX, " Validating buffer...");
1110 LaTeXFeatures features(*this, params(), runparams);
1112 LYXERR(Debug::LATEX, " Buffer validation done.");
1114 // The starting paragraph of the coming rows is the
1115 // first paragraph of the document. (Asger)
1116 if (output_preamble && runparams.nice) {
1117 os << "%% LyX " << lyx_version << " created this file. "
1118 "For more info, see http://www.lyx.org/.\n"
1119 "%% Do not edit unless you really know what "
1121 d->texrow.newline();
1122 d->texrow.newline();
1124 LYXERR(Debug::INFO, "lyx document header finished");
1126 // Don't move this behind the parent_buffer=0 code below,
1127 // because then the macros will not get the right "redefinition"
1128 // flag as they don't see the parent macros which are output before.
1131 // fold macros if possible, still with parent buffer as the
1132 // macros will be put in the prefix anyway.
1133 updateMacroInstances();
1135 // There are a few differences between nice LaTeX and usual files:
1136 // usual is \batchmode and has a
1137 // special input@path to allow the including of figures
1138 // with either \input or \includegraphics (what figinsets do).
1139 // input@path is set when the actual parameter
1140 // original_path is set. This is done for usual tex-file, but not
1141 // for nice-latex-file. (Matthias 250696)
1142 // Note that input@path is only needed for something the user does
1143 // in the preamble, included .tex files or ERT, files included by
1144 // LyX work without it.
1145 if (output_preamble) {
1146 if (!runparams.nice) {
1147 // code for usual, NOT nice-latex-file
1148 os << "\\batchmode\n"; // changed
1149 // from \nonstopmode
1150 d->texrow.newline();
1152 if (!original_path.empty()) {
1154 // We don't know the encoding of inputpath
1155 docstring const inputpath = from_utf8(latex_path(original_path));
1156 os << "\\makeatletter\n"
1157 << "\\def\\input@path{{"
1158 << inputpath << "/}}\n"
1159 << "\\makeatother\n";
1160 d->texrow.newline();
1161 d->texrow.newline();
1162 d->texrow.newline();
1165 // get parent macros (if this buffer has a parent) which will be
1166 // written at the document begin further down.
1167 MacroSet parentMacros;
1168 listParentMacros(parentMacros, features);
1170 // Write the preamble
1171 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1173 runparams.use_japanese = features.isRequired("japanese");
1179 os << "\\begin{document}\n";
1180 d->texrow.newline();
1182 // output the parent macros
1183 MacroSet::iterator it = parentMacros.begin();
1184 MacroSet::iterator end = parentMacros.end();
1185 for (; it != end; ++it)
1186 (*it)->write(os, true);
1187 } // output_preamble
1189 d->texrow.start(paragraphs().begin()->id(), 0);
1191 LYXERR(Debug::INFO, "preamble finished, now the body.");
1193 // if we are doing a real file with body, even if this is the
1194 // child of some other buffer, let's cut the link here.
1195 // This happens for example if only a child document is printed.
1196 Buffer const * save_parent = 0;
1197 if (output_preamble) {
1198 save_parent = d->parent();
1203 latexParagraphs(*this, text(), os, d->texrow, runparams);
1205 // Restore the parenthood if needed
1206 if (output_preamble)
1207 d->setParent(save_parent);
1209 // add this just in case after all the paragraphs
1211 d->texrow.newline();
1213 if (output_preamble) {
1214 os << "\\end{document}\n";
1215 d->texrow.newline();
1216 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1218 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1220 runparams_in.encoding = runparams.encoding;
1222 // Just to be sure. (Asger)
1223 d->texrow.newline();
1225 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1226 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1230 bool Buffer::isLatex() const
1232 return params().documentClass().outputType() == LATEX;
1236 bool Buffer::isLiterate() const
1238 return params().documentClass().outputType() == LITERATE;
1242 bool Buffer::isDocBook() const
1244 return params().documentClass().outputType() == DOCBOOK;
1248 void Buffer::makeDocBookFile(FileName const & fname,
1249 OutputParams const & runparams,
1250 bool const body_only) const
1252 LYXERR(Debug::LATEX, "makeDocBookFile...");
1255 if (!openFileWrite(ofs, fname))
1258 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1262 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1266 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1267 OutputParams const & runparams,
1268 bool const only_body) const
1270 LaTeXFeatures features(*this, params(), runparams);
1275 DocumentClass const & tclass = params().documentClass();
1276 string const top_element = tclass.latexname();
1279 if (runparams.flavor == OutputParams::XML)
1280 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1283 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1286 if (! tclass.class_header().empty())
1287 os << from_ascii(tclass.class_header());
1288 else if (runparams.flavor == OutputParams::XML)
1289 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1290 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1292 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1294 docstring preamble = from_utf8(params().preamble);
1295 if (runparams.flavor != OutputParams::XML ) {
1296 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1297 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1298 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1299 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1302 string const name = runparams.nice
1303 ? changeExtension(absFileName(), ".sgml") : fname;
1304 preamble += features.getIncludedFiles(name);
1305 preamble += features.getLyXSGMLEntities();
1307 if (!preamble.empty()) {
1308 os << "\n [ " << preamble << " ]";
1313 string top = top_element;
1315 if (runparams.flavor == OutputParams::XML)
1316 top += params().language->code();
1318 top += params().language->code().substr(0, 2);
1321 if (!params().options.empty()) {
1323 top += params().options;
1326 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1327 << " file was created by LyX " << lyx_version
1328 << "\n See http://www.lyx.org/ for more information -->\n";
1330 params().documentClass().counters().reset();
1334 sgml::openTag(os, top);
1336 docbookParagraphs(paragraphs(), *this, os, runparams);
1337 sgml::closeTag(os, top_element);
1341 void Buffer::makeLyXHTMLFile(FileName const & fname,
1342 OutputParams const & runparams,
1343 bool const body_only) const
1345 LYXERR(Debug::LATEX, "makeLYXHTMLFile...");
1348 if (!openFileWrite(ofs, fname))
1351 writeLyXHTMLSource(ofs, runparams, body_only);
1355 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1359 void Buffer::writeLyXHTMLSource(odocstream & os,
1360 OutputParams const & runparams,
1361 bool const only_body) const
1363 LaTeXFeatures features(*this, params(), runparams);
1369 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" <<
1370 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1371 // FIXME Language should be set properly.
1372 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
1375 // FIXME Presumably need to set this right
1376 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1377 // FIXME Get this during validation? What about other meta-data?
1378 os << "<title>TBA</title>\n";
1380 os << features.getTClassHTMLPreamble();
1384 docstring const styleinfo = features.getTClassHTMLStyles();
1385 if (!styleinfo.empty()) {
1386 os << "<style type='text/css'>\n";
1390 os << "</head>\n<body>\n";
1393 params().documentClass().counters().reset();
1394 xhtmlParagraphs(paragraphs(), *this, os, runparams);
1396 os << "</body>\n</html>\n";
1400 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1401 // Other flags: -wall -v0 -x
1402 int Buffer::runChktex()
1406 // get LaTeX-Filename
1407 FileName const path(temppath());
1408 string const name = addName(path.absFilename(), latexName());
1409 string const org_path = filePath();
1411 PathChanger p(path); // path to LaTeX file
1412 message(_("Running chktex..."));
1414 // Generate the LaTeX file if neccessary
1415 OutputParams runparams(¶ms().encoding());
1416 runparams.flavor = OutputParams::LATEX;
1417 runparams.nice = false;
1418 makeLaTeXFile(FileName(name), org_path, runparams);
1421 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1422 int const res = chktex.run(terr); // run chktex
1425 Alert::error(_("chktex failure"),
1426 _("Could not run chktex successfully."));
1427 } else if (res > 0) {
1428 ErrorList & errlist = d->errorLists["ChkTeX"];
1430 bufferErrors(terr, errlist);
1441 void Buffer::validate(LaTeXFeatures & features) const
1443 params().validate(features);
1447 for_each(paragraphs().begin(), paragraphs().end(),
1448 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1450 if (lyxerr.debugging(Debug::LATEX)) {
1451 features.showStruct();
1456 void Buffer::getLabelList(vector<docstring> & list) const
1458 // If this is a child document, use the parent's list instead.
1459 Buffer const * const pbuf = d->parent();
1461 pbuf->getLabelList(list);
1466 Toc & toc = d->toc_backend.toc("label");
1467 TocIterator toc_it = toc.begin();
1468 TocIterator end = toc.end();
1469 for (; toc_it != end; ++toc_it) {
1470 if (toc_it->depth() == 0)
1471 list.push_back(toc_it->str());
1476 void Buffer::updateBibfilesCache(UpdateScope scope) const
1478 // If this is a child document, use the parent's cache instead.
1479 Buffer const * const pbuf = d->parent();
1480 if (pbuf && scope != UpdateChildOnly) {
1481 pbuf->updateBibfilesCache();
1485 d->bibfilesCache_.clear();
1486 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1487 if (it->lyxCode() == BIBTEX_CODE) {
1488 InsetBibtex const & inset =
1489 static_cast<InsetBibtex const &>(*it);
1490 support::FileNameList const bibfiles = inset.getBibFiles();
1491 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1494 } else if (it->lyxCode() == INCLUDE_CODE) {
1495 InsetInclude & inset =
1496 static_cast<InsetInclude &>(*it);
1497 inset.updateBibfilesCache();
1498 support::FileNameList const & bibfiles =
1499 inset.getBibfilesCache();
1500 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1505 // the bibinfo cache is now invalid
1506 d->bibinfoCacheValid_ = false;
1510 void Buffer::invalidateBibinfoCache()
1512 d->bibinfoCacheValid_ = false;
1516 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1518 // If this is a child document, use the parent's cache instead.
1519 Buffer const * const pbuf = d->parent();
1520 if (pbuf && scope != UpdateChildOnly)
1521 return pbuf->getBibfilesCache();
1523 // We update the cache when first used instead of at loading time.
1524 if (d->bibfilesCache_.empty())
1525 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1527 return d->bibfilesCache_;
1531 BiblioInfo const & Buffer::masterBibInfo() const
1533 // if this is a child document and the parent is already loaded
1534 // use the parent's list instead [ale990412]
1535 Buffer const * const tmp = masterBuffer();
1538 return tmp->masterBibInfo();
1539 return localBibInfo();
1543 BiblioInfo const & Buffer::localBibInfo() const
1545 if (d->bibinfoCacheValid_) {
1546 support::FileNameList const & bibfilesCache = getBibfilesCache();
1547 // compare the cached timestamps with the actual ones.
1548 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1549 support::FileNameList::const_iterator en = bibfilesCache.end();
1550 for (; ei != en; ++ ei) {
1551 time_t lastw = ei->lastModified();
1552 if (lastw != d->bibfileStatus_[*ei]) {
1553 d->bibinfoCacheValid_ = false;
1554 d->bibfileStatus_[*ei] = lastw;
1560 if (!d->bibinfoCacheValid_) {
1561 d->bibinfo_.clear();
1562 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1563 it->fillWithBibKeys(d->bibinfo_, it);
1564 d->bibinfoCacheValid_ = true;
1570 bool Buffer::isDepClean(string const & name) const
1572 DepClean::const_iterator const it = d->dep_clean.find(name);
1573 if (it == d->dep_clean.end())
1579 void Buffer::markDepClean(string const & name)
1581 d->dep_clean[name] = true;
1585 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1587 switch (cmd.action) {
1588 case LFUN_BUFFER_EXPORT: {
1589 docstring const arg = cmd.argument();
1590 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1592 flag.message(bformat(
1593 _("Don't know how to export to format: %1$s"), arg));
1594 flag.setEnabled(enable);
1598 case LFUN_BRANCH_ACTIVATE:
1599 case LFUN_BRANCH_DEACTIVATE: {
1600 BranchList const & branchList = params().branchlist();
1601 docstring const branchName = cmd.argument();
1602 flag.setEnabled(!branchName.empty()
1603 && branchList.find(branchName));
1607 case LFUN_BUFFER_PRINT:
1608 // if no Buffer is present, then of course we won't be called!
1609 flag.setEnabled(true);
1619 void Buffer::dispatch(string const & command, DispatchResult & result)
1621 return dispatch(lyxaction.lookupFunc(command), result);
1625 // NOTE We can end up here even if we have no GUI, because we are called
1626 // by LyX::exec to handled command-line requests. So we may need to check
1627 // whether we have a GUI or not. The boolean use_gui holds this information.
1628 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1630 // We'll set this back to false if need be.
1631 bool dispatched = true;
1633 switch (func.action) {
1634 case LFUN_BUFFER_EXPORT: {
1635 bool success = doExport(to_utf8(func.argument()), false);
1636 dr.setError(success);
1638 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1643 case LFUN_BRANCH_ACTIVATE:
1644 case LFUN_BRANCH_DEACTIVATE: {
1645 BranchList & branchList = params().branchlist();
1646 docstring const branchName = func.argument();
1647 // the case without a branch name is handled elsewhere
1648 if (branchName.empty()) {
1652 Branch * branch = branchList.find(branchName);
1654 LYXERR0("Branch " << branchName << " does not exist.");
1656 docstring const msg =
1657 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1660 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1662 dr.update(Update::Force);
1667 case LFUN_BUFFER_PRINT: {
1668 // we'll assume there's a problem until we succeed
1670 string target = func.getArg(0);
1671 string target_name = func.getArg(1);
1672 string command = func.getArg(2);
1675 || target_name.empty()
1676 || command.empty()) {
1677 LYXERR0("Unable to parse " << func.argument());
1678 docstring const msg =
1679 bformat(_("Unable to parse \"%1$s\""), func.argument());
1683 if (target != "printer" && target != "file") {
1684 LYXERR0("Unrecognized target \"" << target << '"');
1685 docstring const msg =
1686 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1691 if (!doExport("dvi", true)) {
1692 showPrintError(absFileName());
1693 dr.setMessage(_("Error exporting to DVI."));
1697 // Push directory path.
1698 string const path = temppath();
1699 // Prevent the compiler from optimizing away p
1703 // there are three cases here:
1704 // 1. we print to a file
1705 // 2. we print directly to a printer
1706 // 3. we print using a spool command (print to file first)
1709 string const dviname = changeExtension(latexName(true), "dvi");
1711 if (target == "printer") {
1712 if (!lyxrc.print_spool_command.empty()) {
1713 // case 3: print using a spool
1714 string const psname = changeExtension(dviname,".ps");
1715 command += ' ' + lyxrc.print_to_file
1718 + quoteName(dviname);
1720 string command2 = lyxrc.print_spool_command + ' ';
1721 if (target_name != "default") {
1722 command2 += lyxrc.print_spool_printerprefix
1726 command2 += quoteName(psname);
1728 // If successful, then spool command
1729 res = one.startscript(Systemcall::Wait, command);
1732 // If there's no GUI, we have to wait on this command. Otherwise,
1733 // LyX deletes the temporary directory, and with it the spooled
1734 // file, before it can be printed!!
1735 Systemcall::Starttype stype = use_gui ?
1736 Systemcall::DontWait : Systemcall::Wait;
1737 res = one.startscript(stype, command2);
1740 // case 2: print directly to a printer
1741 if (target_name != "default")
1742 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1744 Systemcall::Starttype stype = use_gui ?
1745 Systemcall::DontWait : Systemcall::Wait;
1746 res = one.startscript(stype, command + quoteName(dviname));
1750 // case 1: print to a file
1751 FileName const filename(makeAbsPath(target_name, filePath()));
1752 FileName const dvifile(makeAbsPath(dviname, path));
1753 if (filename.exists()) {
1754 docstring text = bformat(
1755 _("The file %1$s already exists.\n\n"
1756 "Do you want to overwrite that file?"),
1757 makeDisplayPath(filename.absFilename()));
1758 if (Alert::prompt(_("Overwrite file?"),
1759 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1762 command += ' ' + lyxrc.print_to_file
1763 + quoteName(filename.toFilesystemEncoding())
1765 + quoteName(dvifile.toFilesystemEncoding());
1767 Systemcall::Starttype stype = use_gui ?
1768 Systemcall::DontWait : Systemcall::Wait;
1769 res = one.startscript(stype, command);
1775 dr.setMessage(_("Error running external commands."));
1776 showPrintError(absFileName());
1785 dr.dispatched(dispatched);
1789 void Buffer::changeLanguage(Language const * from, Language const * to)
1791 LASSERT(from, /**/);
1794 for_each(par_iterator_begin(),
1796 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1800 bool Buffer::isMultiLingual() const
1802 ParConstIterator end = par_iterator_end();
1803 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1804 if (it->isMultiLingual(params()))
1811 DocIterator Buffer::getParFromID(int const id) const
1813 Buffer * buf = const_cast<Buffer *>(this);
1815 // John says this is called with id == -1 from undo
1816 lyxerr << "getParFromID(), id: " << id << endl;
1817 return doc_iterator_end(buf);
1820 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1821 if (it.paragraph().id() == id)
1824 return doc_iterator_end(buf);
1828 bool Buffer::hasParWithID(int const id) const
1830 return !getParFromID(id).atEnd();
1834 ParIterator Buffer::par_iterator_begin()
1836 return ParIterator(doc_iterator_begin(this));
1840 ParIterator Buffer::par_iterator_end()
1842 return ParIterator(doc_iterator_end(this));
1846 ParConstIterator Buffer::par_iterator_begin() const
1848 return ParConstIterator(doc_iterator_begin(this));
1852 ParConstIterator Buffer::par_iterator_end() const
1854 return ParConstIterator(doc_iterator_end(this));
1858 Language const * Buffer::language() const
1860 return params().language;
1864 docstring const Buffer::B_(string const & l10n) const
1866 return params().B_(l10n);
1870 bool Buffer::isClean() const
1872 return d->lyx_clean;
1876 bool Buffer::isBakClean() const
1878 return d->bak_clean;
1882 bool Buffer::isExternallyModified(CheckMethod method) const
1884 LASSERT(d->filename.exists(), /**/);
1885 // if method == timestamp, check timestamp before checksum
1886 return (method == checksum_method
1887 || d->timestamp_ != d->filename.lastModified())
1888 && d->checksum_ != d->filename.checksum();
1892 void Buffer::saveCheckSum(FileName const & file) const
1894 if (file.exists()) {
1895 d->timestamp_ = file.lastModified();
1896 d->checksum_ = file.checksum();
1898 // in the case of save to a new file.
1905 void Buffer::markClean() const
1907 if (!d->lyx_clean) {
1908 d->lyx_clean = true;
1911 // if the .lyx file has been saved, we don't need an
1913 d->bak_clean = true;
1917 void Buffer::markBakClean() const
1919 d->bak_clean = true;
1923 void Buffer::setUnnamed(bool flag)
1929 bool Buffer::isUnnamed() const
1935 // FIXME: this function should be moved to buffer_pimpl.C
1936 void Buffer::markDirty()
1939 d->lyx_clean = false;
1942 d->bak_clean = false;
1944 DepClean::iterator it = d->dep_clean.begin();
1945 DepClean::const_iterator const end = d->dep_clean.end();
1947 for (; it != end; ++it)
1952 FileName Buffer::fileName() const
1958 string Buffer::absFileName() const
1960 return d->filename.absFilename();
1964 string Buffer::filePath() const
1966 return d->filename.onlyPath().absFilename() + "/";
1970 bool Buffer::isReadonly() const
1972 return d->read_only;
1976 void Buffer::setParent(Buffer const * buffer)
1978 // Avoids recursive include.
1979 d->setParent(buffer == this ? 0 : buffer);
1984 Buffer const * Buffer::parent() const
1990 void Buffer::collectRelatives(BufferSet & bufs) const
1994 parent()->collectRelatives(bufs);
1996 // loop over children
1997 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1998 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1999 for (; it != end; ++it)
2000 bufs.insert(const_cast<Buffer *>(it->first));
2004 std::vector<Buffer const *> Buffer::allRelatives() const
2007 collectRelatives(bufs);
2008 BufferSet::iterator it = bufs.begin();
2009 std::vector<Buffer const *> ret;
2010 for (; it != bufs.end(); ++it)
2016 Buffer const * Buffer::masterBuffer() const
2018 Buffer const * const pbuf = d->parent();
2022 return pbuf->masterBuffer();
2026 bool Buffer::isChild(Buffer * child) const
2028 return d->children_positions.find(child) != d->children_positions.end();
2032 DocIterator Buffer::firstChildPosition(Buffer const * child)
2034 Impl::BufferPositionMap::iterator it;
2035 it = d->children_positions.find(child);
2036 if (it == d->children_positions.end())
2037 return DocIterator(this);
2042 std::vector<Buffer *> Buffer::getChildren() const
2044 std::vector<Buffer *> clist;
2045 // loop over children
2046 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2047 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2048 for (; it != end; ++it) {
2049 Buffer * child = const_cast<Buffer *>(it->first);
2050 clist.push_back(child);
2051 // there might be grandchildren
2052 std::vector<Buffer *> glist = child->getChildren();
2053 for (vector<Buffer *>::const_iterator git = glist.begin();
2054 git != glist.end(); ++git)
2055 clist.push_back(*git);
2061 template<typename M>
2062 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2067 typename M::iterator it = m.lower_bound(x);
2068 if (it == m.begin())
2076 MacroData const * Buffer::getBufferMacro(docstring const & name,
2077 DocIterator const & pos) const
2079 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2081 // if paragraphs have no macro context set, pos will be empty
2085 // we haven't found anything yet
2086 DocIterator bestPos = par_iterator_begin();
2087 MacroData const * bestData = 0;
2089 // find macro definitions for name
2090 Impl::NamePositionScopeMacroMap::iterator nameIt
2091 = d->macros.find(name);
2092 if (nameIt != d->macros.end()) {
2093 // find last definition in front of pos or at pos itself
2094 Impl::PositionScopeMacroMap::const_iterator it
2095 = greatest_below(nameIt->second, pos);
2096 if (it != nameIt->second.end()) {
2098 // scope ends behind pos?
2099 if (pos < it->second.first) {
2100 // Looks good, remember this. If there
2101 // is no external macro behind this,
2102 // we found the right one already.
2103 bestPos = it->first;
2104 bestData = &it->second.second;
2108 // try previous macro if there is one
2109 if (it == nameIt->second.begin())
2116 // find macros in included files
2117 Impl::PositionScopeBufferMap::const_iterator it
2118 = greatest_below(d->position_to_children, pos);
2119 if (it == d->position_to_children.end())
2120 // no children before
2124 // do we know something better (i.e. later) already?
2125 if (it->first < bestPos )
2128 // scope ends behind pos?
2129 if (pos < it->second.first) {
2130 // look for macro in external file
2131 d->macro_lock = true;
2132 MacroData const * data
2133 = it->second.second->getMacro(name, false);
2134 d->macro_lock = false;
2136 bestPos = it->first;
2142 // try previous file if there is one
2143 if (it == d->position_to_children.begin())
2148 // return the best macro we have found
2153 MacroData const * Buffer::getMacro(docstring const & name,
2154 DocIterator const & pos, bool global) const
2159 // query buffer macros
2160 MacroData const * data = getBufferMacro(name, pos);
2164 // If there is a master buffer, query that
2165 Buffer const * const pbuf = d->parent();
2167 d->macro_lock = true;
2168 MacroData const * macro = pbuf->getMacro(
2169 name, *this, false);
2170 d->macro_lock = false;
2176 data = MacroTable::globalMacros().get(name);
2185 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2187 // set scope end behind the last paragraph
2188 DocIterator scope = par_iterator_begin();
2189 scope.pit() = scope.lastpit() + 1;
2191 return getMacro(name, scope, global);
2195 MacroData const * Buffer::getMacro(docstring const & name,
2196 Buffer const & child, bool global) const
2198 // look where the child buffer is included first
2199 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2200 if (it == d->children_positions.end())
2203 // check for macros at the inclusion position
2204 return getMacro(name, it->second, global);
2208 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2210 pit_type lastpit = it.lastpit();
2212 // look for macros in each paragraph
2213 while (it.pit() <= lastpit) {
2214 Paragraph & par = it.paragraph();
2216 // iterate over the insets of the current paragraph
2217 InsetList const & insets = par.insetList();
2218 InsetList::const_iterator iit = insets.begin();
2219 InsetList::const_iterator end = insets.end();
2220 for (; iit != end; ++iit) {
2221 it.pos() = iit->pos;
2223 // is it a nested text inset?
2224 if (iit->inset->asInsetText()) {
2225 // Inset needs its own scope?
2226 InsetText const * itext = iit->inset->asInsetText();
2227 bool newScope = itext->isMacroScope();
2229 // scope which ends just behind the inset
2230 DocIterator insetScope = it;
2233 // collect macros in inset
2234 it.push_back(CursorSlice(*iit->inset));
2235 updateMacros(it, newScope ? insetScope : scope);
2240 // is it an external file?
2241 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2242 // get buffer of external file
2243 InsetInclude const & inset =
2244 static_cast<InsetInclude const &>(*iit->inset);
2245 d->macro_lock = true;
2246 Buffer * child = inset.getChildBuffer();
2247 d->macro_lock = false;
2251 // register its position, but only when it is
2252 // included first in the buffer
2253 if (d->children_positions.find(child) ==
2254 d->children_positions.end())
2255 d->children_positions[child] = it;
2257 // register child with its scope
2258 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2262 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2266 MathMacroTemplate & macroTemplate =
2267 static_cast<MathMacroTemplate &>(*iit->inset);
2268 MacroContext mc(*this, it);
2269 macroTemplate.updateToContext(mc);
2272 bool valid = macroTemplate.validMacro();
2273 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2274 // then the BufferView's cursor will be invalid in
2275 // some cases which leads to crashes.
2280 d->macros[macroTemplate.name()][it] =
2281 Impl::ScopeMacro(scope, MacroData(*this, it));
2291 void Buffer::updateMacros() const
2296 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2298 // start with empty table
2300 d->children_positions.clear();
2301 d->position_to_children.clear();
2303 // Iterate over buffer, starting with first paragraph
2304 // The scope must be bigger than any lookup DocIterator
2305 // later. For the global lookup, lastpit+1 is used, hence
2306 // we use lastpit+2 here.
2307 DocIterator it = par_iterator_begin();
2308 DocIterator outerScope = it;
2309 outerScope.pit() = outerScope.lastpit() + 2;
2310 updateMacros(it, outerScope);
2314 void Buffer::updateMacroInstances() const
2316 LYXERR(Debug::MACROS, "updateMacroInstances for "
2317 << d->filename.onlyFileName());
2318 DocIterator it = doc_iterator_begin(this);
2319 DocIterator end = doc_iterator_end(this);
2320 for (; it != end; it.forwardPos()) {
2321 // look for MathData cells in InsetMathNest insets
2322 Inset * inset = it.nextInset();
2326 InsetMath * minset = inset->asInsetMath();
2330 // update macro in all cells of the InsetMathNest
2331 DocIterator::idx_type n = minset->nargs();
2332 MacroContext mc = MacroContext(*this, it);
2333 for (DocIterator::idx_type i = 0; i < n; ++i) {
2334 MathData & data = minset->cell(i);
2335 data.updateMacros(0, mc);
2341 void Buffer::listMacroNames(MacroNameSet & macros) const
2346 d->macro_lock = true;
2348 // loop over macro names
2349 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2350 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2351 for (; nameIt != nameEnd; ++nameIt)
2352 macros.insert(nameIt->first);
2354 // loop over children
2355 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2356 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2357 for (; it != end; ++it)
2358 it->first->listMacroNames(macros);
2361 Buffer const * const pbuf = d->parent();
2363 pbuf->listMacroNames(macros);
2365 d->macro_lock = false;
2369 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2371 Buffer const * const pbuf = d->parent();
2376 pbuf->listMacroNames(names);
2379 MacroNameSet::iterator it = names.begin();
2380 MacroNameSet::iterator end = names.end();
2381 for (; it != end; ++it) {
2383 MacroData const * data =
2384 pbuf->getMacro(*it, *this, false);
2386 macros.insert(data);
2388 // we cannot access the original MathMacroTemplate anymore
2389 // here to calls validate method. So we do its work here manually.
2390 // FIXME: somehow make the template accessible here.
2391 if (data->optionals() > 0)
2392 features.require("xargs");
2398 Buffer::References & Buffer::references(docstring const & label)
2401 return const_cast<Buffer *>(masterBuffer())->references(label);
2403 RefCache::iterator it = d->ref_cache_.find(label);
2404 if (it != d->ref_cache_.end())
2405 return it->second.second;
2407 static InsetLabel const * dummy_il = 0;
2408 static References const dummy_refs;
2409 it = d->ref_cache_.insert(
2410 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2411 return it->second.second;
2415 Buffer::References const & Buffer::references(docstring const & label) const
2417 return const_cast<Buffer *>(this)->references(label);
2421 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2423 masterBuffer()->d->ref_cache_[label].first = il;
2427 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2429 return masterBuffer()->d->ref_cache_[label].first;
2433 void Buffer::clearReferenceCache() const
2436 d->ref_cache_.clear();
2440 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2443 //FIXME: This does not work for child documents yet.
2444 LASSERT(code == CITE_CODE, /**/);
2445 // Check if the label 'from' appears more than once
2446 vector<docstring> labels;
2448 BiblioInfo const & keys = masterBibInfo();
2449 BiblioInfo::const_iterator bit = keys.begin();
2450 BiblioInfo::const_iterator bend = keys.end();
2452 for (; bit != bend; ++bit)
2454 labels.push_back(bit->first);
2457 if (count(labels.begin(), labels.end(), from) > 1)
2460 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2461 if (it->lyxCode() == code) {
2462 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2463 docstring const oldValue = inset.getParam(paramName);
2464 if (oldValue == from)
2465 inset.setParam(paramName, to);
2471 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2472 pit_type par_end, bool full_source) const
2474 OutputParams runparams(¶ms().encoding());
2475 runparams.nice = true;
2476 runparams.flavor = params().useXetex ?
2477 OutputParams::XETEX : OutputParams::LATEX;
2478 runparams.linelen = lyxrc.plaintext_linelen;
2479 // No side effect of file copying and image conversion
2480 runparams.dryrun = true;
2483 os << "% " << _("Preview source code") << "\n\n";
2485 d->texrow.newline();
2486 d->texrow.newline();
2488 writeDocBookSource(os, absFileName(), runparams, false);
2490 // latex or literate
2491 writeLaTeXSource(os, string(), runparams, true, true);
2493 runparams.par_begin = par_begin;
2494 runparams.par_end = par_end;
2495 if (par_begin + 1 == par_end) {
2497 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2501 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2502 convert<docstring>(par_begin),
2503 convert<docstring>(par_end - 1))
2510 // output paragraphs
2512 docbookParagraphs(paragraphs(), *this, os, runparams);
2514 // latex or literate
2515 latexParagraphs(*this, text(), os, texrow, runparams);
2520 ErrorList & Buffer::errorList(string const & type) const
2522 static ErrorList emptyErrorList;
2523 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2524 if (I == d->errorLists.end())
2525 return emptyErrorList;
2531 void Buffer::updateTocItem(std::string const & type,
2532 DocIterator const & dit) const
2535 gui_->updateTocItem(type, dit);
2539 void Buffer::structureChanged() const
2542 gui_->structureChanged();
2546 void Buffer::errors(string const & err) const
2553 void Buffer::message(docstring const & msg) const
2560 void Buffer::setBusy(bool on) const
2567 void Buffer::setReadOnly(bool on) const
2570 d->wa_->setReadOnly(on);
2574 void Buffer::updateTitles() const
2577 d->wa_->updateTitles();
2581 void Buffer::resetAutosaveTimers() const
2584 gui_->resetAutosaveTimers();
2588 bool Buffer::hasGuiDelegate() const
2594 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2603 class AutoSaveBuffer : public ForkedProcess {
2606 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2607 : buffer_(buffer), fname_(fname) {}
2609 virtual boost::shared_ptr<ForkedProcess> clone() const
2611 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2616 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2617 from_utf8(fname_.absFilename())));
2618 return run(DontWait);
2622 virtual int generateChild();
2624 Buffer const & buffer_;
2629 int AutoSaveBuffer::generateChild()
2631 // tmp_ret will be located (usually) in /tmp
2632 // will that be a problem?
2633 // Note that this calls ForkedCalls::fork(), so it's
2634 // ok cross-platform.
2635 pid_t const pid = fork();
2636 // If you want to debug the autosave
2637 // you should set pid to -1, and comment out the fork.
2638 if (pid != 0 && pid != -1)
2641 // pid = -1 signifies that lyx was unable
2642 // to fork. But we will do the save
2644 bool failed = false;
2645 FileName const tmp_ret = FileName::tempName("lyxauto");
2646 if (!tmp_ret.empty()) {
2647 buffer_.writeFile(tmp_ret);
2648 // assume successful write of tmp_ret
2649 if (!tmp_ret.moveTo(fname_))
2655 // failed to write/rename tmp_ret so try writing direct
2656 if (!buffer_.writeFile(fname_)) {
2657 // It is dangerous to do this in the child,
2658 // but safe in the parent, so...
2659 if (pid == -1) // emit message signal.
2660 buffer_.message(_("Autosave failed!"));
2664 if (pid == 0) // we are the child so...
2673 FileName Buffer::getAutosaveFilename() const
2675 // if the document is unnamed try to save in the backup dir, else
2676 // in the default document path, and as a last try in the filePath,
2677 // which will most often be the temporary directory
2680 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2681 : lyxrc.backupdir_path;
2682 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2685 string const fname = "#" + d->filename.onlyFileName() + "#";
2686 return makeAbsPath(fname, fpath);
2690 void Buffer::removeAutosaveFile() const
2692 FileName const f = getAutosaveFilename();
2698 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2700 FileName const newauto = getAutosaveFilename();
2701 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2702 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2706 // Perfect target for a thread...
2707 void Buffer::autoSave() const
2709 if (isBakClean() || isReadonly()) {
2710 // We don't save now, but we'll try again later
2711 resetAutosaveTimers();
2715 // emit message signal.
2716 message(_("Autosaving current document..."));
2717 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2721 resetAutosaveTimers();
2725 string Buffer::bufferFormat() const
2727 string format = params().documentClass().outputFormat();
2728 if (format == "latex") {
2729 if (params().useXetex)
2731 if (params().encoding().package() == Encoding::japanese)
2738 string Buffer::getDefaultOutputFormat() const
2740 if (!params().defaultOutputFormat.empty()
2741 && params().defaultOutputFormat != "default")
2742 return params().defaultOutputFormat;
2743 typedef vector<Format const *> Formats;
2744 Formats formats = exportableFormats(true);
2747 || params().useXetex
2748 || params().encoding().package() == Encoding::japanese) {
2749 if (formats.empty())
2751 // return the first we find
2752 return formats.front()->name();
2754 return lyxrc.default_view_format;
2759 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2760 string & result_file) const
2762 string backend_format;
2763 OutputParams runparams(¶ms().encoding());
2764 runparams.flavor = OutputParams::LATEX;
2765 runparams.linelen = lyxrc.plaintext_linelen;
2766 vector<string> backs = backends();
2767 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2768 // Get shortest path to format
2769 Graph::EdgePath path;
2770 for (vector<string>::const_iterator it = backs.begin();
2771 it != backs.end(); ++it) {
2772 Graph::EdgePath p = theConverters().getPath(*it, format);
2773 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2774 backend_format = *it;
2779 runparams.flavor = theConverters().getFlavor(path);
2781 Alert::error(_("Couldn't export file"),
2782 bformat(_("No information for exporting the format %1$s."),
2783 formats.prettyName(format)));
2787 backend_format = format;
2788 // FIXME: Don't hardcode format names here, but use a flag
2789 if (backend_format == "pdflatex")
2790 runparams.flavor = OutputParams::PDFLATEX;
2793 string filename = latexName(false);
2794 filename = addName(temppath(), filename);
2795 filename = changeExtension(filename,
2796 formats.extension(backend_format));
2799 updateMacroInstances();
2801 // Plain text backend
2802 if (backend_format == "text")
2803 writePlaintextFile(*this, FileName(filename), runparams);
2805 else if (backend_format == "xhtml")
2806 makeLyXHTMLFile(FileName(filename), runparams);
2807 else if (backend_format == "lyx")
2808 writeFile(FileName(filename));
2810 else if (isDocBook()) {
2811 runparams.nice = !put_in_tempdir;
2812 makeDocBookFile(FileName(filename), runparams);
2815 else if (backend_format == format) {
2816 runparams.nice = true;
2817 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2819 } else if (!lyxrc.tex_allows_spaces
2820 && contains(filePath(), ' ')) {
2821 Alert::error(_("File name error"),
2822 _("The directory path to the document cannot contain spaces."));
2825 runparams.nice = false;
2826 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2830 string const error_type = (format == "program")
2831 ? "Build" : bufferFormat();
2832 ErrorList & error_list = d->errorLists[error_type];
2833 string const ext = formats.extension(format);
2834 FileName const tmp_result_file(changeExtension(filename, ext));
2835 bool const success = theConverters().convert(this, FileName(filename),
2836 tmp_result_file, FileName(absFileName()), backend_format, format,
2838 // Emit the signal to show the error list.
2839 if (format != backend_format)
2844 if (put_in_tempdir) {
2845 result_file = tmp_result_file.absFilename();
2849 result_file = changeExtension(absFileName(), ext);
2850 // We need to copy referenced files (e. g. included graphics
2851 // if format == "dvi") to the result dir.
2852 vector<ExportedFile> const files =
2853 runparams.exportdata->externalFiles(format);
2854 string const dest = onlyPath(result_file);
2855 CopyStatus status = SUCCESS;
2856 for (vector<ExportedFile>::const_iterator it = files.begin();
2857 it != files.end() && status != CANCEL; ++it) {
2858 string const fmt = formats.getFormatFromFile(it->sourceName);
2859 status = copyFile(fmt, it->sourceName,
2860 makeAbsPath(it->exportName, dest),
2861 it->exportName, status == FORCE);
2863 if (status == CANCEL) {
2864 message(_("Document export cancelled."));
2865 } else if (tmp_result_file.exists()) {
2866 // Finally copy the main file
2867 status = copyFile(format, tmp_result_file,
2868 FileName(result_file), result_file,
2870 message(bformat(_("Document exported as %1$s "
2872 formats.prettyName(format),
2873 makeDisplayPath(result_file)));
2875 // This must be a dummy converter like fax (bug 1888)
2876 message(bformat(_("Document exported as %1$s"),
2877 formats.prettyName(format)));
2884 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2887 return doExport(format, put_in_tempdir, result_file);
2891 bool Buffer::preview(string const & format) const
2894 if (!doExport(format, true, result_file))
2896 return formats.view(*this, FileName(result_file), format);
2900 bool Buffer::isExportable(string const & format) const
2902 vector<string> backs = backends();
2903 for (vector<string>::const_iterator it = backs.begin();
2904 it != backs.end(); ++it)
2905 if (theConverters().isReachable(*it, format))
2911 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2913 vector<string> backs = backends();
2914 vector<Format const *> result =
2915 theConverters().getReachable(backs[0], only_viewable, true);
2916 for (vector<string>::const_iterator it = backs.begin() + 1;
2917 it != backs.end(); ++it) {
2918 vector<Format const *> r =
2919 theConverters().getReachable(*it, only_viewable, false);
2920 result.insert(result.end(), r.begin(), r.end());
2926 vector<string> Buffer::backends() const
2929 if (params().baseClass()->isTeXClassAvailable()) {
2930 v.push_back(bufferFormat());
2931 // FIXME: Don't hardcode format names here, but use a flag
2932 if (v.back() == "latex")
2933 v.push_back("pdflatex");
2935 v.push_back("text");
2936 v.push_back("xhtml");
2942 bool Buffer::readFileHelper(FileName const & s)
2944 // File information about normal file
2946 docstring const file = makeDisplayPath(s.absFilename(), 50);
2947 docstring text = bformat(_("The specified document\n%1$s"
2948 "\ncould not be read."), file);
2949 Alert::error(_("Could not read document"), text);
2953 // Check if emergency save file exists and is newer.
2954 FileName const e(s.absFilename() + ".emergency");
2956 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2957 docstring const file = makeDisplayPath(s.absFilename(), 20);
2958 docstring const text =
2959 bformat(_("An emergency save of the document "
2961 "Recover emergency save?"), file);
2962 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2963 _("&Recover"), _("&Load Original"),
2967 // the file is not saved if we load the emergency file.
2977 // Now check if autosave file is newer.
2978 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2980 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2981 docstring const file = makeDisplayPath(s.absFilename(), 20);
2982 docstring const text =
2983 bformat(_("The backup of the document "
2984 "%1$s is newer.\n\nLoad the "
2985 "backup instead?"), file);
2986 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2987 _("&Load backup"), _("Load &original"),
2991 // the file is not saved if we load the autosave file.
2995 // Here we delete the autosave
3006 bool Buffer::loadLyXFile(FileName const & s)
3008 if (s.isReadableFile()) {
3009 if (readFileHelper(s)) {
3010 lyxvc().file_found_hook(s);
3011 if (!s.isWritable())
3016 docstring const file = makeDisplayPath(s.absFilename(), 20);
3017 // Here we probably should run
3018 if (LyXVC::file_not_found_hook(s)) {
3019 docstring const text =
3020 bformat(_("Do you want to retrieve the document"
3021 " %1$s from version control?"), file);
3022 int const ret = Alert::prompt(_("Retrieve from version control?"),
3023 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3026 // How can we know _how_ to do the checkout?
3027 // With the current VC support it has to be,
3028 // a RCS file since CVS do not have special ,v files.
3030 return loadLyXFile(s);
3038 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3040 TeXErrors::Errors::const_iterator cit = terr.begin();
3041 TeXErrors::Errors::const_iterator end = terr.end();
3043 for (; cit != end; ++cit) {
3046 int errorRow = cit->error_in_line;
3047 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3053 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3054 } while (found && id_start == id_end && pos_start == pos_end);
3056 errorList.push_back(ErrorItem(cit->error_desc,
3057 cit->error_text, id_start, pos_start, pos_end));
3062 void Buffer::setBuffersForInsets() const
3064 inset().setBuffer(const_cast<Buffer &>(*this));
3068 void Buffer::updateLabels(UpdateScope scope) const
3070 // Use the master text class also for child documents
3071 Buffer const * const master = masterBuffer();
3072 DocumentClass const & textclass = master->params().documentClass();
3074 // keep the buffers to be children in this set. If the call from the
3075 // master comes back we can see which of them were actually seen (i.e.
3076 // via an InsetInclude). The remaining ones in the set need still be updated.
3077 static std::set<Buffer const *> bufToUpdate;
3078 if (scope == UpdateMaster) {
3079 // If this is a child document start with the master
3080 if (master != this) {
3081 bufToUpdate.insert(this);
3082 master->updateLabels();
3083 // Do this here in case the master has no gui associated with it. Then,
3084 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3088 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3089 if (bufToUpdate.find(this) == bufToUpdate.end())
3093 // start over the counters in the master
3094 textclass.counters().reset();
3097 // update will be done below for this buffer
3098 bufToUpdate.erase(this);
3100 // update all caches
3101 clearReferenceCache();
3104 Buffer & cbuf = const_cast<Buffer &>(*this);
3106 LASSERT(!text().paragraphs().empty(), /**/);
3109 ParIterator parit = cbuf.par_iterator_begin();
3110 updateLabels(parit);
3113 // TocBackend update will be done later.
3116 cbuf.tocBackend().update();
3117 if (scope == UpdateMaster)
3118 cbuf.structureChanged();
3122 static depth_type getDepth(DocIterator const & it)
3124 depth_type depth = 0;
3125 for (size_t i = 0 ; i < it.depth() ; ++i)
3126 if (!it[i].inset().inMathed())
3127 depth += it[i].paragraph().getDepth() + 1;
3128 // remove 1 since the outer inset does not count
3132 static depth_type getItemDepth(ParIterator const & it)
3134 Paragraph const & par = *it;
3135 LabelType const labeltype = par.layout().labeltype;
3137 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3140 // this will hold the lowest depth encountered up to now.
3141 depth_type min_depth = getDepth(it);
3142 ParIterator prev_it = it;
3145 --prev_it.top().pit();
3147 // start of nested inset: go to outer par
3149 if (prev_it.empty()) {
3150 // start of document: nothing to do
3155 // We search for the first paragraph with same label
3156 // that is not more deeply nested.
3157 Paragraph & prev_par = *prev_it;
3158 depth_type const prev_depth = getDepth(prev_it);
3159 if (labeltype == prev_par.layout().labeltype) {
3160 if (prev_depth < min_depth)
3161 return prev_par.itemdepth + 1;
3162 if (prev_depth == min_depth)
3163 return prev_par.itemdepth;
3165 min_depth = min(min_depth, prev_depth);
3166 // small optimization: if we are at depth 0, we won't
3167 // find anything else
3168 if (prev_depth == 0)
3174 static bool needEnumCounterReset(ParIterator const & it)
3176 Paragraph const & par = *it;
3177 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3178 depth_type const cur_depth = par.getDepth();
3179 ParIterator prev_it = it;
3180 while (prev_it.pit()) {
3181 --prev_it.top().pit();
3182 Paragraph const & prev_par = *prev_it;
3183 if (prev_par.getDepth() <= cur_depth)
3184 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3186 // start of nested inset: reset
3191 // set the label of a paragraph. This includes the counters.
3192 static void setLabel(Buffer const & buf, ParIterator & it)
3194 BufferParams const & bp = buf.masterBuffer()->params();
3195 DocumentClass const & textclass = bp.documentClass();
3196 Paragraph & par = it.paragraph();
3197 Layout const & layout = par.layout();
3198 Counters & counters = textclass.counters();
3200 if (par.params().startOfAppendix()) {
3201 // FIXME: only the counter corresponding to toplevel
3202 // sectionning should be reset
3204 counters.appendix(true);
3206 par.params().appendix(counters.appendix());
3208 // Compute the item depth of the paragraph
3209 par.itemdepth = getItemDepth(it);
3211 if (layout.margintype == MARGIN_MANUAL
3212 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3213 if (par.params().labelWidthString().empty())
3214 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3216 par.params().labelWidthString(docstring());
3219 switch(layout.labeltype) {
3221 if (layout.toclevel <= bp.secnumdepth
3222 && (layout.latextype != LATEX_ENVIRONMENT
3223 || isFirstInSequence(it.pit(), it.plist()))) {
3224 counters.step(layout.counter);
3225 par.params().labelString(
3226 par.expandLabel(layout, bp));
3228 par.params().labelString(docstring());
3231 case LABEL_ITEMIZE: {
3232 // At some point of time we should do something more
3233 // clever here, like:
3234 // par.params().labelString(
3235 // bp.user_defined_bullet(par.itemdepth).getText());
3236 // for now, use a simple hardcoded label
3237 docstring itemlabel;
3238 switch (par.itemdepth) {
3240 itemlabel = char_type(0x2022);
3243 itemlabel = char_type(0x2013);
3246 itemlabel = char_type(0x2217);
3249 itemlabel = char_type(0x2219); // or 0x00b7
3252 par.params().labelString(itemlabel);
3256 case LABEL_ENUMERATE: {
3257 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3259 switch (par.itemdepth) {
3268 enumcounter += "iv";
3271 // not a valid enumdepth...
3275 // Maybe we have to reset the enumeration counter.
3276 if (needEnumCounterReset(it))
3277 counters.reset(enumcounter);
3278 counters.step(enumcounter);
3280 par.params().labelString(counters.theCounter(enumcounter));
3285 case LABEL_SENSITIVE: {
3286 string const & type = counters.current_float();
3287 docstring full_label;
3289 full_label = buf.B_("Senseless!!! ");
3291 docstring name = buf.B_(textclass.floats().getType(type).name());
3292 if (counters.hasCounter(from_utf8(type))) {
3293 counters.step(from_utf8(type));
3294 full_label = bformat(from_ascii("%1$s %2$s:"),
3296 counters.theCounter(from_utf8(type)));
3298 full_label = bformat(from_ascii("%1$s #:"), name);
3300 par.params().labelString(full_label);
3304 case LABEL_NO_LABEL:
3305 par.params().labelString(docstring());
3309 case LABEL_TOP_ENVIRONMENT:
3310 case LABEL_CENTERED_TOP_ENVIRONMENT:
3313 par.params().labelString(
3314 par.translateIfPossible(layout.labelstring(), bp));
3320 void Buffer::updateLabels(ParIterator & parit) const
3322 LASSERT(parit.pit() == 0, /**/);
3324 // set the position of the text in the buffer to be able
3325 // to resolve macros in it. This has nothing to do with
3326 // labels, but by putting it here we avoid implementing
3327 // a whole bunch of traversal routines just for this call.
3328 parit.text()->setMacrocontextPosition(parit);
3330 depth_type maxdepth = 0;
3331 pit_type const lastpit = parit.lastpit();
3332 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3333 // reduce depth if necessary
3334 parit->params().depth(min(parit->params().depth(), maxdepth));
3335 maxdepth = parit->getMaxDepthAfter();
3337 // set the counter for this paragraph
3338 setLabel(*this, parit);
3341 InsetList::const_iterator iit = parit->insetList().begin();
3342 InsetList::const_iterator end = parit->insetList().end();
3343 for (; iit != end; ++iit) {
3344 parit.pos() = iit->pos;
3345 iit->inset->updateLabels(parit);
3351 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3352 docstring & word) const
3354 bool inword = false;
3355 bool ignoreword = false;
3357 // Go backward a bit if needed in order to return the word currently
3358 // pointed by 'from'.
3359 while (from && from.pos() && isLetter(from))
3361 // OK, we start from here.
3363 while (to.depth()) {
3370 lang_code = to.paragraph().getFontSettings(params(),
3371 to.pos()).language()->code();
3373 // Insets like optional hyphens and ligature
3374 // break are part of a word.
3375 if (!to.paragraph().isInset(to.pos())) {
3376 char_type const c = to.paragraph().getChar(to.pos());
3381 } else { // !isLetter(cur)
3382 if (inword && !word.empty() && !ignoreword)
3394 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3395 WordLangTuple & word_lang, docstring_list & suggestions) const
3398 SpellChecker::Result res = SpellChecker::OK;
3399 SpellChecker * speller = theSpellChecker();
3400 suggestions.clear();
3402 while (nextWord(from, to, word)) {
3404 string lang_code = lyxrc.spellchecker_use_alt_lang
3405 ? lyxrc.spellchecker_alt_lang
3406 : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3407 WordLangTuple wl(word, lang_code);
3408 res = speller->check(wl);
3409 // ... just bail out if the spellchecker reports an error.
3410 if (!speller->error().empty()) {
3411 throw ExceptionMessage(WarningException,
3412 _("The spellchecker has failed."), speller->error());
3414 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3420 while (!(word = speller->nextMiss()).empty())
3421 suggestions.push_back(word);