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 docstring styleinfo = features.getTClassHTMLPreamble();
1381 if (!styleinfo.empty()) {
1382 os << "<style type='text/css'>\n";
1386 os << "</head>\n<body>\n";
1389 params().documentClass().counters().reset();
1390 xhtmlParagraphs(paragraphs(), *this, os, runparams);
1392 os << "</body>\n</html>\n";
1396 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1397 // Other flags: -wall -v0 -x
1398 int Buffer::runChktex()
1402 // get LaTeX-Filename
1403 FileName const path(temppath());
1404 string const name = addName(path.absFilename(), latexName());
1405 string const org_path = filePath();
1407 PathChanger p(path); // path to LaTeX file
1408 message(_("Running chktex..."));
1410 // Generate the LaTeX file if neccessary
1411 OutputParams runparams(¶ms().encoding());
1412 runparams.flavor = OutputParams::LATEX;
1413 runparams.nice = false;
1414 makeLaTeXFile(FileName(name), org_path, runparams);
1417 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1418 int const res = chktex.run(terr); // run chktex
1421 Alert::error(_("chktex failure"),
1422 _("Could not run chktex successfully."));
1423 } else if (res > 0) {
1424 ErrorList & errlist = d->errorLists["ChkTeX"];
1426 bufferErrors(terr, errlist);
1437 void Buffer::validate(LaTeXFeatures & features) const
1439 params().validate(features);
1443 for_each(paragraphs().begin(), paragraphs().end(),
1444 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1446 if (lyxerr.debugging(Debug::LATEX)) {
1447 features.showStruct();
1452 void Buffer::getLabelList(vector<docstring> & list) const
1454 // If this is a child document, use the parent's list instead.
1455 Buffer const * const pbuf = d->parent();
1457 pbuf->getLabelList(list);
1462 Toc & toc = d->toc_backend.toc("label");
1463 TocIterator toc_it = toc.begin();
1464 TocIterator end = toc.end();
1465 for (; toc_it != end; ++toc_it) {
1466 if (toc_it->depth() == 0)
1467 list.push_back(toc_it->str());
1472 void Buffer::updateBibfilesCache(UpdateScope scope) const
1474 // If this is a child document, use the parent's cache instead.
1475 Buffer const * const pbuf = d->parent();
1476 if (pbuf && scope != UpdateChildOnly) {
1477 pbuf->updateBibfilesCache();
1481 d->bibfilesCache_.clear();
1482 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1483 if (it->lyxCode() == BIBTEX_CODE) {
1484 InsetBibtex const & inset =
1485 static_cast<InsetBibtex const &>(*it);
1486 support::FileNameList const bibfiles = inset.getBibFiles();
1487 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1490 } else if (it->lyxCode() == INCLUDE_CODE) {
1491 InsetInclude & inset =
1492 static_cast<InsetInclude &>(*it);
1493 inset.updateBibfilesCache();
1494 support::FileNameList const & bibfiles =
1495 inset.getBibfilesCache();
1496 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1501 // the bibinfo cache is now invalid
1502 d->bibinfoCacheValid_ = false;
1506 void Buffer::invalidateBibinfoCache()
1508 d->bibinfoCacheValid_ = false;
1512 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1514 // If this is a child document, use the parent's cache instead.
1515 Buffer const * const pbuf = d->parent();
1516 if (pbuf && scope != UpdateChildOnly)
1517 return pbuf->getBibfilesCache();
1519 // We update the cache when first used instead of at loading time.
1520 if (d->bibfilesCache_.empty())
1521 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1523 return d->bibfilesCache_;
1527 BiblioInfo const & Buffer::masterBibInfo() const
1529 // if this is a child document and the parent is already loaded
1530 // use the parent's list instead [ale990412]
1531 Buffer const * const tmp = masterBuffer();
1534 return tmp->masterBibInfo();
1535 return localBibInfo();
1539 BiblioInfo const & Buffer::localBibInfo() const
1541 if (d->bibinfoCacheValid_) {
1542 support::FileNameList const & bibfilesCache = getBibfilesCache();
1543 // compare the cached timestamps with the actual ones.
1544 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1545 support::FileNameList::const_iterator en = bibfilesCache.end();
1546 for (; ei != en; ++ ei) {
1547 time_t lastw = ei->lastModified();
1548 if (lastw != d->bibfileStatus_[*ei]) {
1549 d->bibinfoCacheValid_ = false;
1550 d->bibfileStatus_[*ei] = lastw;
1556 if (!d->bibinfoCacheValid_) {
1557 d->bibinfo_.clear();
1558 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1559 it->fillWithBibKeys(d->bibinfo_, it);
1560 d->bibinfoCacheValid_ = true;
1566 bool Buffer::isDepClean(string const & name) const
1568 DepClean::const_iterator const it = d->dep_clean.find(name);
1569 if (it == d->dep_clean.end())
1575 void Buffer::markDepClean(string const & name)
1577 d->dep_clean[name] = true;
1581 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1583 switch (cmd.action) {
1584 case LFUN_BUFFER_EXPORT: {
1585 docstring const arg = cmd.argument();
1586 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1588 flag.message(bformat(
1589 _("Don't know how to export to format: %1$s"), arg));
1590 flag.setEnabled(enable);
1594 case LFUN_BRANCH_ACTIVATE:
1595 case LFUN_BRANCH_DEACTIVATE: {
1596 BranchList const & branchList = params().branchlist();
1597 docstring const branchName = cmd.argument();
1598 flag.setEnabled(!branchName.empty()
1599 && branchList.find(branchName));
1603 case LFUN_BUFFER_PRINT:
1604 // if no Buffer is present, then of course we won't be called!
1605 flag.setEnabled(true);
1615 void Buffer::dispatch(string const & command, DispatchResult & result)
1617 return dispatch(lyxaction.lookupFunc(command), result);
1621 // NOTE We can end up here even if we have no GUI, because we are called
1622 // by LyX::exec to handled command-line requests. So we may need to check
1623 // whether we have a GUI or not. The boolean use_gui holds this information.
1624 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1626 // We'll set this back to false if need be.
1627 bool dispatched = true;
1629 switch (func.action) {
1630 case LFUN_BUFFER_EXPORT: {
1631 bool success = doExport(to_utf8(func.argument()), false);
1632 dr.setError(success);
1634 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1639 case LFUN_BRANCH_ACTIVATE:
1640 case LFUN_BRANCH_DEACTIVATE: {
1641 BranchList & branchList = params().branchlist();
1642 docstring const branchName = func.argument();
1643 // the case without a branch name is handled elsewhere
1644 if (branchName.empty()) {
1648 Branch * branch = branchList.find(branchName);
1650 LYXERR0("Branch " << branchName << " does not exist.");
1652 docstring const msg =
1653 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1656 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1658 dr.update(Update::Force);
1663 case LFUN_BUFFER_PRINT: {
1664 // we'll assume there's a problem until we succeed
1666 string target = func.getArg(0);
1667 string target_name = func.getArg(1);
1668 string command = func.getArg(2);
1671 || target_name.empty()
1672 || command.empty()) {
1673 LYXERR0("Unable to parse " << func.argument());
1674 docstring const msg =
1675 bformat(_("Unable to parse \"%1$s\""), func.argument());
1679 if (target != "printer" && target != "file") {
1680 LYXERR0("Unrecognized target \"" << target << '"');
1681 docstring const msg =
1682 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1687 if (!doExport("dvi", true)) {
1688 showPrintError(absFileName());
1689 dr.setMessage(_("Error exporting to DVI."));
1693 // Push directory path.
1694 string const path = temppath();
1695 // Prevent the compiler from optimizing away p
1699 // there are three cases here:
1700 // 1. we print to a file
1701 // 2. we print directly to a printer
1702 // 3. we print using a spool command (print to file first)
1705 string const dviname = changeExtension(latexName(true), "dvi");
1707 if (target == "printer") {
1708 if (!lyxrc.print_spool_command.empty()) {
1709 // case 3: print using a spool
1710 string const psname = changeExtension(dviname,".ps");
1711 command += ' ' + lyxrc.print_to_file
1714 + quoteName(dviname);
1716 string command2 = lyxrc.print_spool_command + ' ';
1717 if (target_name != "default") {
1718 command2 += lyxrc.print_spool_printerprefix
1722 command2 += quoteName(psname);
1724 // If successful, then spool command
1725 res = one.startscript(Systemcall::Wait, command);
1728 // If there's no GUI, we have to wait on this command. Otherwise,
1729 // LyX deletes the temporary directory, and with it the spooled
1730 // file, before it can be printed!!
1731 Systemcall::Starttype stype = use_gui ?
1732 Systemcall::DontWait : Systemcall::Wait;
1733 res = one.startscript(stype, command2);
1736 // case 2: print directly to a printer
1737 if (target_name != "default")
1738 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1740 Systemcall::Starttype stype = use_gui ?
1741 Systemcall::DontWait : Systemcall::Wait;
1742 res = one.startscript(stype, command + quoteName(dviname));
1746 // case 1: print to a file
1747 FileName const filename(makeAbsPath(target_name, filePath()));
1748 FileName const dvifile(makeAbsPath(dviname, path));
1749 if (filename.exists()) {
1750 docstring text = bformat(
1751 _("The file %1$s already exists.\n\n"
1752 "Do you want to overwrite that file?"),
1753 makeDisplayPath(filename.absFilename()));
1754 if (Alert::prompt(_("Overwrite file?"),
1755 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1758 command += ' ' + lyxrc.print_to_file
1759 + quoteName(filename.toFilesystemEncoding())
1761 + quoteName(dvifile.toFilesystemEncoding());
1763 Systemcall::Starttype stype = use_gui ?
1764 Systemcall::DontWait : Systemcall::Wait;
1765 res = one.startscript(stype, command);
1771 dr.setMessage(_("Error running external commands."));
1772 showPrintError(absFileName());
1781 dr.dispatched(dispatched);
1785 void Buffer::changeLanguage(Language const * from, Language const * to)
1787 LASSERT(from, /**/);
1790 for_each(par_iterator_begin(),
1792 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1796 bool Buffer::isMultiLingual() const
1798 ParConstIterator end = par_iterator_end();
1799 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1800 if (it->isMultiLingual(params()))
1807 DocIterator Buffer::getParFromID(int const id) const
1809 Buffer * buf = const_cast<Buffer *>(this);
1811 // John says this is called with id == -1 from undo
1812 lyxerr << "getParFromID(), id: " << id << endl;
1813 return doc_iterator_end(buf);
1816 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1817 if (it.paragraph().id() == id)
1820 return doc_iterator_end(buf);
1824 bool Buffer::hasParWithID(int const id) const
1826 return !getParFromID(id).atEnd();
1830 ParIterator Buffer::par_iterator_begin()
1832 return ParIterator(doc_iterator_begin(this));
1836 ParIterator Buffer::par_iterator_end()
1838 return ParIterator(doc_iterator_end(this));
1842 ParConstIterator Buffer::par_iterator_begin() const
1844 return ParConstIterator(doc_iterator_begin(this));
1848 ParConstIterator Buffer::par_iterator_end() const
1850 return ParConstIterator(doc_iterator_end(this));
1854 Language const * Buffer::language() const
1856 return params().language;
1860 docstring const Buffer::B_(string const & l10n) const
1862 return params().B_(l10n);
1866 bool Buffer::isClean() const
1868 return d->lyx_clean;
1872 bool Buffer::isBakClean() const
1874 return d->bak_clean;
1878 bool Buffer::isExternallyModified(CheckMethod method) const
1880 LASSERT(d->filename.exists(), /**/);
1881 // if method == timestamp, check timestamp before checksum
1882 return (method == checksum_method
1883 || d->timestamp_ != d->filename.lastModified())
1884 && d->checksum_ != d->filename.checksum();
1888 void Buffer::saveCheckSum(FileName const & file) const
1890 if (file.exists()) {
1891 d->timestamp_ = file.lastModified();
1892 d->checksum_ = file.checksum();
1894 // in the case of save to a new file.
1901 void Buffer::markClean() const
1903 if (!d->lyx_clean) {
1904 d->lyx_clean = true;
1907 // if the .lyx file has been saved, we don't need an
1909 d->bak_clean = true;
1913 void Buffer::markBakClean() const
1915 d->bak_clean = true;
1919 void Buffer::setUnnamed(bool flag)
1925 bool Buffer::isUnnamed() const
1931 // FIXME: this function should be moved to buffer_pimpl.C
1932 void Buffer::markDirty()
1935 d->lyx_clean = false;
1938 d->bak_clean = false;
1940 DepClean::iterator it = d->dep_clean.begin();
1941 DepClean::const_iterator const end = d->dep_clean.end();
1943 for (; it != end; ++it)
1948 FileName Buffer::fileName() const
1954 string Buffer::absFileName() const
1956 return d->filename.absFilename();
1960 string Buffer::filePath() const
1962 return d->filename.onlyPath().absFilename() + "/";
1966 bool Buffer::isReadonly() const
1968 return d->read_only;
1972 void Buffer::setParent(Buffer const * buffer)
1974 // Avoids recursive include.
1975 d->setParent(buffer == this ? 0 : buffer);
1980 Buffer const * Buffer::parent() const
1986 void Buffer::collectRelatives(BufferSet & bufs) const
1990 parent()->collectRelatives(bufs);
1992 // loop over children
1993 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1994 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1995 for (; it != end; ++it)
1996 bufs.insert(const_cast<Buffer *>(it->first));
2000 std::vector<Buffer const *> Buffer::allRelatives() const
2003 collectRelatives(bufs);
2004 BufferSet::iterator it = bufs.begin();
2005 std::vector<Buffer const *> ret;
2006 for (; it != bufs.end(); ++it)
2012 Buffer const * Buffer::masterBuffer() const
2014 Buffer const * const pbuf = d->parent();
2018 return pbuf->masterBuffer();
2022 bool Buffer::isChild(Buffer * child) const
2024 return d->children_positions.find(child) != d->children_positions.end();
2028 DocIterator Buffer::firstChildPosition(Buffer const * child)
2030 Impl::BufferPositionMap::iterator it;
2031 it = d->children_positions.find(child);
2032 if (it == d->children_positions.end())
2033 return DocIterator(this);
2038 std::vector<Buffer *> Buffer::getChildren() const
2040 std::vector<Buffer *> clist;
2041 // loop over children
2042 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2043 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2044 for (; it != end; ++it) {
2045 Buffer * child = const_cast<Buffer *>(it->first);
2046 clist.push_back(child);
2047 // there might be grandchildren
2048 std::vector<Buffer *> glist = child->getChildren();
2049 for (vector<Buffer *>::const_iterator git = glist.begin();
2050 git != glist.end(); ++git)
2051 clist.push_back(*git);
2057 template<typename M>
2058 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2063 typename M::iterator it = m.lower_bound(x);
2064 if (it == m.begin())
2072 MacroData const * Buffer::getBufferMacro(docstring const & name,
2073 DocIterator const & pos) const
2075 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2077 // if paragraphs have no macro context set, pos will be empty
2081 // we haven't found anything yet
2082 DocIterator bestPos = par_iterator_begin();
2083 MacroData const * bestData = 0;
2085 // find macro definitions for name
2086 Impl::NamePositionScopeMacroMap::iterator nameIt
2087 = d->macros.find(name);
2088 if (nameIt != d->macros.end()) {
2089 // find last definition in front of pos or at pos itself
2090 Impl::PositionScopeMacroMap::const_iterator it
2091 = greatest_below(nameIt->second, pos);
2092 if (it != nameIt->second.end()) {
2094 // scope ends behind pos?
2095 if (pos < it->second.first) {
2096 // Looks good, remember this. If there
2097 // is no external macro behind this,
2098 // we found the right one already.
2099 bestPos = it->first;
2100 bestData = &it->second.second;
2104 // try previous macro if there is one
2105 if (it == nameIt->second.begin())
2112 // find macros in included files
2113 Impl::PositionScopeBufferMap::const_iterator it
2114 = greatest_below(d->position_to_children, pos);
2115 if (it == d->position_to_children.end())
2116 // no children before
2120 // do we know something better (i.e. later) already?
2121 if (it->first < bestPos )
2124 // scope ends behind pos?
2125 if (pos < it->second.first) {
2126 // look for macro in external file
2127 d->macro_lock = true;
2128 MacroData const * data
2129 = it->second.second->getMacro(name, false);
2130 d->macro_lock = false;
2132 bestPos = it->first;
2138 // try previous file if there is one
2139 if (it == d->position_to_children.begin())
2144 // return the best macro we have found
2149 MacroData const * Buffer::getMacro(docstring const & name,
2150 DocIterator const & pos, bool global) const
2155 // query buffer macros
2156 MacroData const * data = getBufferMacro(name, pos);
2160 // If there is a master buffer, query that
2161 Buffer const * const pbuf = d->parent();
2163 d->macro_lock = true;
2164 MacroData const * macro = pbuf->getMacro(
2165 name, *this, false);
2166 d->macro_lock = false;
2172 data = MacroTable::globalMacros().get(name);
2181 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2183 // set scope end behind the last paragraph
2184 DocIterator scope = par_iterator_begin();
2185 scope.pit() = scope.lastpit() + 1;
2187 return getMacro(name, scope, global);
2191 MacroData const * Buffer::getMacro(docstring const & name,
2192 Buffer const & child, bool global) const
2194 // look where the child buffer is included first
2195 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2196 if (it == d->children_positions.end())
2199 // check for macros at the inclusion position
2200 return getMacro(name, it->second, global);
2204 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2206 pit_type lastpit = it.lastpit();
2208 // look for macros in each paragraph
2209 while (it.pit() <= lastpit) {
2210 Paragraph & par = it.paragraph();
2212 // iterate over the insets of the current paragraph
2213 InsetList const & insets = par.insetList();
2214 InsetList::const_iterator iit = insets.begin();
2215 InsetList::const_iterator end = insets.end();
2216 for (; iit != end; ++iit) {
2217 it.pos() = iit->pos;
2219 // is it a nested text inset?
2220 if (iit->inset->asInsetText()) {
2221 // Inset needs its own scope?
2222 InsetText const * itext = iit->inset->asInsetText();
2223 bool newScope = itext->isMacroScope();
2225 // scope which ends just behind the inset
2226 DocIterator insetScope = it;
2229 // collect macros in inset
2230 it.push_back(CursorSlice(*iit->inset));
2231 updateMacros(it, newScope ? insetScope : scope);
2236 // is it an external file?
2237 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2238 // get buffer of external file
2239 InsetInclude const & inset =
2240 static_cast<InsetInclude const &>(*iit->inset);
2241 d->macro_lock = true;
2242 Buffer * child = inset.getChildBuffer();
2243 d->macro_lock = false;
2247 // register its position, but only when it is
2248 // included first in the buffer
2249 if (d->children_positions.find(child) ==
2250 d->children_positions.end())
2251 d->children_positions[child] = it;
2253 // register child with its scope
2254 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2258 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2262 MathMacroTemplate & macroTemplate =
2263 static_cast<MathMacroTemplate &>(*iit->inset);
2264 MacroContext mc(*this, it);
2265 macroTemplate.updateToContext(mc);
2268 bool valid = macroTemplate.validMacro();
2269 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2270 // then the BufferView's cursor will be invalid in
2271 // some cases which leads to crashes.
2276 d->macros[macroTemplate.name()][it] =
2277 Impl::ScopeMacro(scope, MacroData(*this, it));
2287 void Buffer::updateMacros() const
2292 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2294 // start with empty table
2296 d->children_positions.clear();
2297 d->position_to_children.clear();
2299 // Iterate over buffer, starting with first paragraph
2300 // The scope must be bigger than any lookup DocIterator
2301 // later. For the global lookup, lastpit+1 is used, hence
2302 // we use lastpit+2 here.
2303 DocIterator it = par_iterator_begin();
2304 DocIterator outerScope = it;
2305 outerScope.pit() = outerScope.lastpit() + 2;
2306 updateMacros(it, outerScope);
2310 void Buffer::updateMacroInstances() const
2312 LYXERR(Debug::MACROS, "updateMacroInstances for "
2313 << d->filename.onlyFileName());
2314 DocIterator it = doc_iterator_begin(this);
2315 DocIterator end = doc_iterator_end(this);
2316 for (; it != end; it.forwardPos()) {
2317 // look for MathData cells in InsetMathNest insets
2318 Inset * inset = it.nextInset();
2322 InsetMath * minset = inset->asInsetMath();
2326 // update macro in all cells of the InsetMathNest
2327 DocIterator::idx_type n = minset->nargs();
2328 MacroContext mc = MacroContext(*this, it);
2329 for (DocIterator::idx_type i = 0; i < n; ++i) {
2330 MathData & data = minset->cell(i);
2331 data.updateMacros(0, mc);
2337 void Buffer::listMacroNames(MacroNameSet & macros) const
2342 d->macro_lock = true;
2344 // loop over macro names
2345 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2346 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2347 for (; nameIt != nameEnd; ++nameIt)
2348 macros.insert(nameIt->first);
2350 // loop over children
2351 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2352 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2353 for (; it != end; ++it)
2354 it->first->listMacroNames(macros);
2357 Buffer const * const pbuf = d->parent();
2359 pbuf->listMacroNames(macros);
2361 d->macro_lock = false;
2365 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2367 Buffer const * const pbuf = d->parent();
2372 pbuf->listMacroNames(names);
2375 MacroNameSet::iterator it = names.begin();
2376 MacroNameSet::iterator end = names.end();
2377 for (; it != end; ++it) {
2379 MacroData const * data =
2380 pbuf->getMacro(*it, *this, false);
2382 macros.insert(data);
2384 // we cannot access the original MathMacroTemplate anymore
2385 // here to calls validate method. So we do its work here manually.
2386 // FIXME: somehow make the template accessible here.
2387 if (data->optionals() > 0)
2388 features.require("xargs");
2394 Buffer::References & Buffer::references(docstring const & label)
2397 return const_cast<Buffer *>(masterBuffer())->references(label);
2399 RefCache::iterator it = d->ref_cache_.find(label);
2400 if (it != d->ref_cache_.end())
2401 return it->second.second;
2403 static InsetLabel const * dummy_il = 0;
2404 static References const dummy_refs;
2405 it = d->ref_cache_.insert(
2406 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2407 return it->second.second;
2411 Buffer::References const & Buffer::references(docstring const & label) const
2413 return const_cast<Buffer *>(this)->references(label);
2417 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2419 masterBuffer()->d->ref_cache_[label].first = il;
2423 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2425 return masterBuffer()->d->ref_cache_[label].first;
2429 void Buffer::clearReferenceCache() const
2432 d->ref_cache_.clear();
2436 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2439 //FIXME: This does not work for child documents yet.
2440 LASSERT(code == CITE_CODE, /**/);
2441 // Check if the label 'from' appears more than once
2442 vector<docstring> labels;
2444 BiblioInfo const & keys = masterBibInfo();
2445 BiblioInfo::const_iterator bit = keys.begin();
2446 BiblioInfo::const_iterator bend = keys.end();
2448 for (; bit != bend; ++bit)
2450 labels.push_back(bit->first);
2453 if (count(labels.begin(), labels.end(), from) > 1)
2456 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2457 if (it->lyxCode() == code) {
2458 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2459 docstring const oldValue = inset.getParam(paramName);
2460 if (oldValue == from)
2461 inset.setParam(paramName, to);
2467 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2468 pit_type par_end, bool full_source) const
2470 OutputParams runparams(¶ms().encoding());
2471 runparams.nice = true;
2472 runparams.flavor = params().useXetex ?
2473 OutputParams::XETEX : OutputParams::LATEX;
2474 runparams.linelen = lyxrc.plaintext_linelen;
2475 // No side effect of file copying and image conversion
2476 runparams.dryrun = true;
2479 os << "% " << _("Preview source code") << "\n\n";
2481 d->texrow.newline();
2482 d->texrow.newline();
2484 writeDocBookSource(os, absFileName(), runparams, false);
2486 // latex or literate
2487 writeLaTeXSource(os, string(), runparams, true, true);
2489 runparams.par_begin = par_begin;
2490 runparams.par_end = par_end;
2491 if (par_begin + 1 == par_end) {
2493 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2497 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2498 convert<docstring>(par_begin),
2499 convert<docstring>(par_end - 1))
2506 // output paragraphs
2508 docbookParagraphs(paragraphs(), *this, os, runparams);
2510 // latex or literate
2511 latexParagraphs(*this, text(), os, texrow, runparams);
2516 ErrorList & Buffer::errorList(string const & type) const
2518 static ErrorList emptyErrorList;
2519 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2520 if (I == d->errorLists.end())
2521 return emptyErrorList;
2527 void Buffer::updateTocItem(std::string const & type,
2528 DocIterator const & dit) const
2531 gui_->updateTocItem(type, dit);
2535 void Buffer::structureChanged() const
2538 gui_->structureChanged();
2542 void Buffer::errors(string const & err) const
2549 void Buffer::message(docstring const & msg) const
2556 void Buffer::setBusy(bool on) const
2563 void Buffer::setReadOnly(bool on) const
2566 d->wa_->setReadOnly(on);
2570 void Buffer::updateTitles() const
2573 d->wa_->updateTitles();
2577 void Buffer::resetAutosaveTimers() const
2580 gui_->resetAutosaveTimers();
2584 bool Buffer::hasGuiDelegate() const
2590 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2599 class AutoSaveBuffer : public ForkedProcess {
2602 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2603 : buffer_(buffer), fname_(fname) {}
2605 virtual boost::shared_ptr<ForkedProcess> clone() const
2607 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2612 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2613 from_utf8(fname_.absFilename())));
2614 return run(DontWait);
2618 virtual int generateChild();
2620 Buffer const & buffer_;
2625 int AutoSaveBuffer::generateChild()
2627 // tmp_ret will be located (usually) in /tmp
2628 // will that be a problem?
2629 // Note that this calls ForkedCalls::fork(), so it's
2630 // ok cross-platform.
2631 pid_t const pid = fork();
2632 // If you want to debug the autosave
2633 // you should set pid to -1, and comment out the fork.
2634 if (pid != 0 && pid != -1)
2637 // pid = -1 signifies that lyx was unable
2638 // to fork. But we will do the save
2640 bool failed = false;
2641 FileName const tmp_ret = FileName::tempName("lyxauto");
2642 if (!tmp_ret.empty()) {
2643 buffer_.writeFile(tmp_ret);
2644 // assume successful write of tmp_ret
2645 if (!tmp_ret.moveTo(fname_))
2651 // failed to write/rename tmp_ret so try writing direct
2652 if (!buffer_.writeFile(fname_)) {
2653 // It is dangerous to do this in the child,
2654 // but safe in the parent, so...
2655 if (pid == -1) // emit message signal.
2656 buffer_.message(_("Autosave failed!"));
2660 if (pid == 0) // we are the child so...
2669 FileName Buffer::getAutosaveFilename() const
2671 // if the document is unnamed try to save in the backup dir, else
2672 // in the default document path, and as a last try in the filePath,
2673 // which will most often be the temporary directory
2676 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2677 : lyxrc.backupdir_path;
2678 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2681 string const fname = "#" + d->filename.onlyFileName() + "#";
2682 return makeAbsPath(fname, fpath);
2686 void Buffer::removeAutosaveFile() const
2688 FileName const f = getAutosaveFilename();
2694 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2696 FileName const newauto = getAutosaveFilename();
2697 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2698 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2702 // Perfect target for a thread...
2703 void Buffer::autoSave() const
2705 if (isBakClean() || isReadonly()) {
2706 // We don't save now, but we'll try again later
2707 resetAutosaveTimers();
2711 // emit message signal.
2712 message(_("Autosaving current document..."));
2713 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2717 resetAutosaveTimers();
2721 string Buffer::bufferFormat() const
2723 string format = params().documentClass().outputFormat();
2724 if (format == "latex") {
2725 if (params().useXetex)
2727 if (params().encoding().package() == Encoding::japanese)
2734 string Buffer::getDefaultOutputFormat() const
2736 if (!params().defaultOutputFormat.empty()
2737 && params().defaultOutputFormat != "default")
2738 return params().defaultOutputFormat;
2739 typedef vector<Format const *> Formats;
2740 Formats formats = exportableFormats(true);
2743 || params().useXetex
2744 || params().encoding().package() == Encoding::japanese) {
2745 if (formats.empty())
2747 // return the first we find
2748 return formats.front()->name();
2750 return lyxrc.default_view_format;
2755 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2756 string & result_file) const
2758 string backend_format;
2759 OutputParams runparams(¶ms().encoding());
2760 runparams.flavor = OutputParams::LATEX;
2761 runparams.linelen = lyxrc.plaintext_linelen;
2762 vector<string> backs = backends();
2763 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2764 // Get shortest path to format
2765 Graph::EdgePath path;
2766 for (vector<string>::const_iterator it = backs.begin();
2767 it != backs.end(); ++it) {
2768 Graph::EdgePath p = theConverters().getPath(*it, format);
2769 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2770 backend_format = *it;
2775 runparams.flavor = theConverters().getFlavor(path);
2777 Alert::error(_("Couldn't export file"),
2778 bformat(_("No information for exporting the format %1$s."),
2779 formats.prettyName(format)));
2783 backend_format = format;
2784 // FIXME: Don't hardcode format names here, but use a flag
2785 if (backend_format == "pdflatex")
2786 runparams.flavor = OutputParams::PDFLATEX;
2789 string filename = latexName(false);
2790 filename = addName(temppath(), filename);
2791 filename = changeExtension(filename,
2792 formats.extension(backend_format));
2795 updateMacroInstances();
2797 // Plain text backend
2798 if (backend_format == "text")
2799 writePlaintextFile(*this, FileName(filename), runparams);
2801 else if (backend_format == "xhtml")
2802 makeLyXHTMLFile(FileName(filename), runparams);
2803 else if (backend_format == "lyx")
2804 writeFile(FileName(filename));
2806 else if (isDocBook()) {
2807 runparams.nice = !put_in_tempdir;
2808 makeDocBookFile(FileName(filename), runparams);
2811 else if (backend_format == format) {
2812 runparams.nice = true;
2813 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2815 } else if (!lyxrc.tex_allows_spaces
2816 && contains(filePath(), ' ')) {
2817 Alert::error(_("File name error"),
2818 _("The directory path to the document cannot contain spaces."));
2821 runparams.nice = false;
2822 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2826 string const error_type = (format == "program")
2827 ? "Build" : bufferFormat();
2828 ErrorList & error_list = d->errorLists[error_type];
2829 string const ext = formats.extension(format);
2830 FileName const tmp_result_file(changeExtension(filename, ext));
2831 bool const success = theConverters().convert(this, FileName(filename),
2832 tmp_result_file, FileName(absFileName()), backend_format, format,
2834 // Emit the signal to show the error list.
2835 if (format != backend_format)
2840 if (put_in_tempdir) {
2841 result_file = tmp_result_file.absFilename();
2845 result_file = changeExtension(absFileName(), ext);
2846 // We need to copy referenced files (e. g. included graphics
2847 // if format == "dvi") to the result dir.
2848 vector<ExportedFile> const files =
2849 runparams.exportdata->externalFiles(format);
2850 string const dest = onlyPath(result_file);
2851 CopyStatus status = SUCCESS;
2852 for (vector<ExportedFile>::const_iterator it = files.begin();
2853 it != files.end() && status != CANCEL; ++it) {
2854 string const fmt = formats.getFormatFromFile(it->sourceName);
2855 status = copyFile(fmt, it->sourceName,
2856 makeAbsPath(it->exportName, dest),
2857 it->exportName, status == FORCE);
2859 if (status == CANCEL) {
2860 message(_("Document export cancelled."));
2861 } else if (tmp_result_file.exists()) {
2862 // Finally copy the main file
2863 status = copyFile(format, tmp_result_file,
2864 FileName(result_file), result_file,
2866 message(bformat(_("Document exported as %1$s "
2868 formats.prettyName(format),
2869 makeDisplayPath(result_file)));
2871 // This must be a dummy converter like fax (bug 1888)
2872 message(bformat(_("Document exported as %1$s"),
2873 formats.prettyName(format)));
2880 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2883 return doExport(format, put_in_tempdir, result_file);
2887 bool Buffer::preview(string const & format) const
2890 if (!doExport(format, true, result_file))
2892 return formats.view(*this, FileName(result_file), format);
2896 bool Buffer::isExportable(string const & format) const
2898 vector<string> backs = backends();
2899 for (vector<string>::const_iterator it = backs.begin();
2900 it != backs.end(); ++it)
2901 if (theConverters().isReachable(*it, format))
2907 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2909 vector<string> backs = backends();
2910 vector<Format const *> result =
2911 theConverters().getReachable(backs[0], only_viewable, true);
2912 for (vector<string>::const_iterator it = backs.begin() + 1;
2913 it != backs.end(); ++it) {
2914 vector<Format const *> r =
2915 theConverters().getReachable(*it, only_viewable, false);
2916 result.insert(result.end(), r.begin(), r.end());
2922 vector<string> Buffer::backends() const
2925 if (params().baseClass()->isTeXClassAvailable()) {
2926 v.push_back(bufferFormat());
2927 // FIXME: Don't hardcode format names here, but use a flag
2928 if (v.back() == "latex")
2929 v.push_back("pdflatex");
2931 v.push_back("text");
2932 v.push_back("xhtml");
2938 bool Buffer::readFileHelper(FileName const & s)
2940 // File information about normal file
2942 docstring const file = makeDisplayPath(s.absFilename(), 50);
2943 docstring text = bformat(_("The specified document\n%1$s"
2944 "\ncould not be read."), file);
2945 Alert::error(_("Could not read document"), text);
2949 // Check if emergency save file exists and is newer.
2950 FileName const e(s.absFilename() + ".emergency");
2952 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2953 docstring const file = makeDisplayPath(s.absFilename(), 20);
2954 docstring const text =
2955 bformat(_("An emergency save of the document "
2957 "Recover emergency save?"), file);
2958 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2959 _("&Recover"), _("&Load Original"),
2963 // the file is not saved if we load the emergency file.
2973 // Now check if autosave file is newer.
2974 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2976 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2977 docstring const file = makeDisplayPath(s.absFilename(), 20);
2978 docstring const text =
2979 bformat(_("The backup of the document "
2980 "%1$s is newer.\n\nLoad the "
2981 "backup instead?"), file);
2982 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2983 _("&Load backup"), _("Load &original"),
2987 // the file is not saved if we load the autosave file.
2991 // Here we delete the autosave
3002 bool Buffer::loadLyXFile(FileName const & s)
3004 if (s.isReadableFile()) {
3005 if (readFileHelper(s)) {
3006 lyxvc().file_found_hook(s);
3007 if (!s.isWritable())
3012 docstring const file = makeDisplayPath(s.absFilename(), 20);
3013 // Here we probably should run
3014 if (LyXVC::file_not_found_hook(s)) {
3015 docstring const text =
3016 bformat(_("Do you want to retrieve the document"
3017 " %1$s from version control?"), file);
3018 int const ret = Alert::prompt(_("Retrieve from version control?"),
3019 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3022 // How can we know _how_ to do the checkout?
3023 // With the current VC support it has to be,
3024 // a RCS file since CVS do not have special ,v files.
3026 return loadLyXFile(s);
3034 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3036 TeXErrors::Errors::const_iterator cit = terr.begin();
3037 TeXErrors::Errors::const_iterator end = terr.end();
3039 for (; cit != end; ++cit) {
3042 int errorRow = cit->error_in_line;
3043 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3049 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3050 } while (found && id_start == id_end && pos_start == pos_end);
3052 errorList.push_back(ErrorItem(cit->error_desc,
3053 cit->error_text, id_start, pos_start, pos_end));
3058 void Buffer::setBuffersForInsets() const
3060 inset().setBuffer(const_cast<Buffer &>(*this));
3064 void Buffer::updateLabels(UpdateScope scope) const
3066 // Use the master text class also for child documents
3067 Buffer const * const master = masterBuffer();
3068 DocumentClass const & textclass = master->params().documentClass();
3070 // keep the buffers to be children in this set. If the call from the
3071 // master comes back we can see which of them were actually seen (i.e.
3072 // via an InsetInclude). The remaining ones in the set need still be updated.
3073 static std::set<Buffer const *> bufToUpdate;
3074 if (scope == UpdateMaster) {
3075 // If this is a child document start with the master
3076 if (master != this) {
3077 bufToUpdate.insert(this);
3078 master->updateLabels();
3079 // Do this here in case the master has no gui associated with it. Then,
3080 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3084 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3085 if (bufToUpdate.find(this) == bufToUpdate.end())
3089 // start over the counters in the master
3090 textclass.counters().reset();
3093 // update will be done below for this buffer
3094 bufToUpdate.erase(this);
3096 // update all caches
3097 clearReferenceCache();
3100 Buffer & cbuf = const_cast<Buffer &>(*this);
3102 LASSERT(!text().paragraphs().empty(), /**/);
3105 ParIterator parit = cbuf.par_iterator_begin();
3106 updateLabels(parit);
3109 // TocBackend update will be done later.
3112 cbuf.tocBackend().update();
3113 if (scope == UpdateMaster)
3114 cbuf.structureChanged();
3118 static depth_type getDepth(DocIterator const & it)
3120 depth_type depth = 0;
3121 for (size_t i = 0 ; i < it.depth() ; ++i)
3122 if (!it[i].inset().inMathed())
3123 depth += it[i].paragraph().getDepth() + 1;
3124 // remove 1 since the outer inset does not count
3128 static depth_type getItemDepth(ParIterator const & it)
3130 Paragraph const & par = *it;
3131 LabelType const labeltype = par.layout().labeltype;
3133 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3136 // this will hold the lowest depth encountered up to now.
3137 depth_type min_depth = getDepth(it);
3138 ParIterator prev_it = it;
3141 --prev_it.top().pit();
3143 // start of nested inset: go to outer par
3145 if (prev_it.empty()) {
3146 // start of document: nothing to do
3151 // We search for the first paragraph with same label
3152 // that is not more deeply nested.
3153 Paragraph & prev_par = *prev_it;
3154 depth_type const prev_depth = getDepth(prev_it);
3155 if (labeltype == prev_par.layout().labeltype) {
3156 if (prev_depth < min_depth)
3157 return prev_par.itemdepth + 1;
3158 if (prev_depth == min_depth)
3159 return prev_par.itemdepth;
3161 min_depth = min(min_depth, prev_depth);
3162 // small optimization: if we are at depth 0, we won't
3163 // find anything else
3164 if (prev_depth == 0)
3170 static bool needEnumCounterReset(ParIterator const & it)
3172 Paragraph const & par = *it;
3173 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3174 depth_type const cur_depth = par.getDepth();
3175 ParIterator prev_it = it;
3176 while (prev_it.pit()) {
3177 --prev_it.top().pit();
3178 Paragraph const & prev_par = *prev_it;
3179 if (prev_par.getDepth() <= cur_depth)
3180 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3182 // start of nested inset: reset
3187 // set the label of a paragraph. This includes the counters.
3188 static void setLabel(Buffer const & buf, ParIterator & it)
3190 BufferParams const & bp = buf.masterBuffer()->params();
3191 DocumentClass const & textclass = bp.documentClass();
3192 Paragraph & par = it.paragraph();
3193 Layout const & layout = par.layout();
3194 Counters & counters = textclass.counters();
3196 if (par.params().startOfAppendix()) {
3197 // FIXME: only the counter corresponding to toplevel
3198 // sectionning should be reset
3200 counters.appendix(true);
3202 par.params().appendix(counters.appendix());
3204 // Compute the item depth of the paragraph
3205 par.itemdepth = getItemDepth(it);
3207 if (layout.margintype == MARGIN_MANUAL
3208 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3209 if (par.params().labelWidthString().empty())
3210 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3212 par.params().labelWidthString(docstring());
3215 switch(layout.labeltype) {
3217 if (layout.toclevel <= bp.secnumdepth
3218 && (layout.latextype != LATEX_ENVIRONMENT
3219 || isFirstInSequence(it.pit(), it.plist()))) {
3220 counters.step(layout.counter);
3221 par.params().labelString(
3222 par.expandLabel(layout, bp));
3224 par.params().labelString(docstring());
3227 case LABEL_ITEMIZE: {
3228 // At some point of time we should do something more
3229 // clever here, like:
3230 // par.params().labelString(
3231 // bp.user_defined_bullet(par.itemdepth).getText());
3232 // for now, use a simple hardcoded label
3233 docstring itemlabel;
3234 switch (par.itemdepth) {
3236 itemlabel = char_type(0x2022);
3239 itemlabel = char_type(0x2013);
3242 itemlabel = char_type(0x2217);
3245 itemlabel = char_type(0x2219); // or 0x00b7
3248 par.params().labelString(itemlabel);
3252 case LABEL_ENUMERATE: {
3253 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3255 switch (par.itemdepth) {
3264 enumcounter += "iv";
3267 // not a valid enumdepth...
3271 // Maybe we have to reset the enumeration counter.
3272 if (needEnumCounterReset(it))
3273 counters.reset(enumcounter);
3274 counters.step(enumcounter);
3276 par.params().labelString(counters.theCounter(enumcounter));
3281 case LABEL_SENSITIVE: {
3282 string const & type = counters.current_float();
3283 docstring full_label;
3285 full_label = buf.B_("Senseless!!! ");
3287 docstring name = buf.B_(textclass.floats().getType(type).name());
3288 if (counters.hasCounter(from_utf8(type))) {
3289 counters.step(from_utf8(type));
3290 full_label = bformat(from_ascii("%1$s %2$s:"),
3292 counters.theCounter(from_utf8(type)));
3294 full_label = bformat(from_ascii("%1$s #:"), name);
3296 par.params().labelString(full_label);
3300 case LABEL_NO_LABEL:
3301 par.params().labelString(docstring());
3305 case LABEL_TOP_ENVIRONMENT:
3306 case LABEL_CENTERED_TOP_ENVIRONMENT:
3309 par.params().labelString(
3310 par.translateIfPossible(layout.labelstring(), bp));
3316 void Buffer::updateLabels(ParIterator & parit) const
3318 LASSERT(parit.pit() == 0, /**/);
3320 // set the position of the text in the buffer to be able
3321 // to resolve macros in it. This has nothing to do with
3322 // labels, but by putting it here we avoid implementing
3323 // a whole bunch of traversal routines just for this call.
3324 parit.text()->setMacrocontextPosition(parit);
3326 depth_type maxdepth = 0;
3327 pit_type const lastpit = parit.lastpit();
3328 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3329 // reduce depth if necessary
3330 parit->params().depth(min(parit->params().depth(), maxdepth));
3331 maxdepth = parit->getMaxDepthAfter();
3333 // set the counter for this paragraph
3334 setLabel(*this, parit);
3337 InsetList::const_iterator iit = parit->insetList().begin();
3338 InsetList::const_iterator end = parit->insetList().end();
3339 for (; iit != end; ++iit) {
3340 parit.pos() = iit->pos;
3341 iit->inset->updateLabels(parit);
3347 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3348 docstring & word) const
3350 bool inword = false;
3351 bool ignoreword = false;
3353 // Go backward a bit if needed in order to return the word currently
3354 // pointed by 'from'.
3355 while (from && from.pos() && isLetter(from))
3357 // OK, we start from here.
3359 while (to.depth()) {
3366 lang_code = to.paragraph().getFontSettings(params(),
3367 to.pos()).language()->code();
3369 // Insets like optional hyphens and ligature
3370 // break are part of a word.
3371 if (!to.paragraph().isInset(to.pos())) {
3372 char_type const c = to.paragraph().getChar(to.pos());
3377 } else { // !isLetter(cur)
3378 if (inword && !word.empty() && !ignoreword)
3390 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3391 WordLangTuple & word_lang, docstring_list & suggestions) const
3394 SpellChecker::Result res = SpellChecker::OK;
3395 SpellChecker * speller = theSpellChecker();
3396 suggestions.clear();
3398 while (nextWord(from, to, word)) {
3400 string lang_code = lyxrc.spellchecker_use_alt_lang
3401 ? lyxrc.spellchecker_alt_lang
3402 : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3403 WordLangTuple wl(word, lang_code);
3404 res = speller->check(wl);
3405 // ... just bail out if the spellchecker reports an error.
3406 if (!speller->error().empty()) {
3407 throw ExceptionMessage(WarningException,
3408 _("The spellchecker has failed."), speller->error());
3410 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3416 while (!(word = speller->nextMiss()).empty())
3417 suggestions.push_back(word);