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.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.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 = 369; // vfr: add author ids to list of authors
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 =
443 makeLatexName(exportFileName());
444 return no_path ? latex_name.onlyFileName()
445 : latex_name.absFilename();
449 FileName Buffer::exportFileName() const
451 docstring const branch_suffix =
452 params().branchlist().getFilenameSuffix();
453 if (branch_suffix.empty())
456 string const name = fileName().onlyFileNameWithoutExt()
457 + to_utf8(branch_suffix);
458 FileName res(fileName().onlyPath().absFilename() + "/" + name);
459 res.changeExtension(fileName().extension());
465 string Buffer::logName(LogType * type) const
467 string const filename = latexName(false);
469 if (filename.empty()) {
475 string const path = temppath();
477 FileName const fname(addName(temppath(),
478 onlyFilename(changeExtension(filename,
481 // FIXME: how do we know this is the name of the build log?
482 FileName const bname(
483 addName(path, onlyFilename(
484 changeExtension(filename,
485 formats.extension(bufferFormat()) + ".out"))));
487 // Also consider the master buffer log file
488 FileName masterfname = fname;
490 if (masterBuffer() != this) {
491 string const mlogfile = masterBuffer()->logName(&mtype);
492 masterfname = FileName(mlogfile);
495 // If no Latex log or Build log is newer, show Build log
496 if (bname.exists() &&
497 ((!fname.exists() && !masterfname.exists())
498 || (fname.lastModified() < bname.lastModified()
499 && masterfname.lastModified() < bname.lastModified()))) {
500 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
503 return bname.absFilename();
504 // If we have a newer master file log or only a master log, show this
505 } else if (fname != masterfname
506 && (!fname.exists() && (masterfname.exists()
507 || fname.lastModified() < masterfname.lastModified()))) {
508 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
511 return masterfname.absFilename();
513 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
516 return fname.absFilename();
520 void Buffer::setReadonly(bool const flag)
522 if (d->read_only != flag) {
529 void Buffer::setFileName(string const & newfile)
531 d->filename = makeAbsPath(newfile);
532 setReadonly(d->filename.isReadOnly());
537 int Buffer::readHeader(Lexer & lex)
539 int unknown_tokens = 0;
541 int begin_header_line = -1;
543 // Initialize parameters that may be/go lacking in header:
544 params().branchlist().clear();
545 params().preamble.erase();
546 params().options.erase();
547 params().master.erase();
548 params().float_placement.erase();
549 params().paperwidth.erase();
550 params().paperheight.erase();
551 params().leftmargin.erase();
552 params().rightmargin.erase();
553 params().topmargin.erase();
554 params().bottommargin.erase();
555 params().headheight.erase();
556 params().headsep.erase();
557 params().footskip.erase();
558 params().columnsep.erase();
559 params().fontsCJK.erase();
560 params().listings_params.clear();
561 params().clearLayoutModules();
562 params().clearRemovedModules();
563 params().pdfoptions().clear();
564 params().indiceslist().clear();
565 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
567 for (int i = 0; i < 4; ++i) {
568 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
569 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
572 ErrorList & errorList = d->errorLists["Parse"];
581 if (token == "\\end_header")
585 if (token == "\\begin_header") {
586 begin_header_line = line;
590 LYXERR(Debug::PARSER, "Handling document header token: `"
593 string unknown = params().readToken(lex, token, d->filename.onlyPath());
594 if (!unknown.empty()) {
595 if (unknown[0] != '\\' && token == "\\textclass") {
596 Alert::warning(_("Unknown document class"),
597 bformat(_("Using the default document class, because the "
598 "class %1$s is unknown."), from_utf8(unknown)));
601 docstring const s = bformat(_("Unknown token: "
605 errorList.push_back(ErrorItem(_("Document header error"),
610 if (begin_header_line) {
611 docstring const s = _("\\begin_header is missing");
612 errorList.push_back(ErrorItem(_("Document header error"),
616 params().makeDocumentClass();
618 return unknown_tokens;
623 // changed to be public and have one parameter
624 // Returns true if "\end_document" is not read (Asger)
625 bool Buffer::readDocument(Lexer & lex)
627 ErrorList & errorList = d->errorLists["Parse"];
630 if (!lex.checkFor("\\begin_document")) {
631 docstring const s = _("\\begin_document is missing");
632 errorList.push_back(ErrorItem(_("Document header error"),
636 // we are reading in a brand new document
637 LASSERT(paragraphs().empty(), /**/);
641 if (params().outputChanges) {
642 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
643 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
644 LaTeXFeatures::isAvailable("xcolor");
646 if (!dvipost && !xcolorulem) {
647 Alert::warning(_("Changes not shown in LaTeX output"),
648 _("Changes will not be highlighted in LaTeX output, "
649 "because neither dvipost nor xcolor/ulem are installed.\n"
650 "Please install these packages or redefine "
651 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
652 } else if (!xcolorulem) {
653 Alert::warning(_("Changes not shown in LaTeX output"),
654 _("Changes will not be highlighted in LaTeX output "
655 "when using pdflatex, because xcolor and ulem are not installed.\n"
656 "Please install both packages or redefine "
657 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
661 if (!params().master.empty()) {
662 FileName const master_file = makeAbsPath(params().master,
663 onlyPath(absFileName()));
664 if (isLyXFilename(master_file.absFilename())) {
666 checkAndLoadLyXFile(master_file, true);
668 // necessary e.g. after a reload
669 // to re-register the child (bug 5873)
670 // FIXME: clean up updateMacros (here, only
671 // child registering is needed).
672 master->updateMacros();
673 // set master as master buffer, but only
674 // if we are a real child
675 if (master->isChild(this))
677 // if the master is not fully loaded
678 // it is probably just loading this
679 // child. No warning needed then.
680 else if (master->isFullyLoaded())
681 LYXERR0("The master '"
683 << "' assigned to this document ("
685 << ") does not include "
686 "this document. Ignoring the master assignment.");
692 bool const res = text().read(lex, errorList, d->inset);
695 updateMacroInstances();
700 bool Buffer::readString(string const & s)
702 params().compressed = false;
704 // remove dummy empty par
705 paragraphs().clear();
709 FileName const name = FileName::tempName("Buffer_readString");
710 switch (readFile(lex, name, true)) {
714 // We need to call lyx2lyx, so write the input to a file
715 ofstream os(name.toFilesystemEncoding().c_str());
718 return readFile(name);
728 bool Buffer::readFile(FileName const & filename)
730 FileName fname(filename);
732 params().compressed = fname.isZippedFile();
734 // remove dummy empty par
735 paragraphs().clear();
738 if (readFile(lex, fname) != success)
745 bool Buffer::isFullyLoaded() const
747 return d->file_fully_loaded;
751 void Buffer::setFullyLoaded(bool value)
753 d->file_fully_loaded = value;
757 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
760 LASSERT(!filename.empty(), /**/);
762 // the first (non-comment) token _must_ be...
763 if (!lex.checkFor("\\lyxformat")) {
764 Alert::error(_("Document format failure"),
765 bformat(_("%1$s is not a readable LyX document."),
766 from_utf8(filename.absFilename())));
772 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
773 // if present remove ".," from string.
774 size_t dot = tmp_format.find_first_of(".,");
775 //lyxerr << " dot found at " << dot << endl;
776 if (dot != string::npos)
777 tmp_format.erase(dot, 1);
778 int const file_format = convert<int>(tmp_format);
779 //lyxerr << "format: " << file_format << endl;
781 // save timestamp and checksum of the original disk file, making sure
782 // to not overwrite them with those of the file created in the tempdir
783 // when it has to be converted to the current format.
785 // Save the timestamp and checksum of disk file. If filename is an
786 // emergency file, save the timestamp and checksum of the original lyx file
787 // because isExternallyModified will check for this file. (BUG4193)
788 string diskfile = filename.absFilename();
789 if (suffixIs(diskfile, ".emergency"))
790 diskfile = diskfile.substr(0, diskfile.size() - 10);
791 saveCheckSum(FileName(diskfile));
794 if (file_format != LYX_FORMAT) {
797 // lyx2lyx would fail
800 FileName const tmpfile = FileName::tempName("Buffer_readFile");
801 if (tmpfile.empty()) {
802 Alert::error(_("Conversion failed"),
803 bformat(_("%1$s is from a different"
804 " version of LyX, but a temporary"
805 " file for converting it could"
807 from_utf8(filename.absFilename())));
810 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
811 if (lyx2lyx.empty()) {
812 Alert::error(_("Conversion script not found"),
813 bformat(_("%1$s is from a different"
814 " version of LyX, but the"
815 " conversion script lyx2lyx"
816 " could not be found."),
817 from_utf8(filename.absFilename())));
820 ostringstream command;
821 command << os::python()
822 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
823 << " -t " << convert<string>(LYX_FORMAT)
824 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
825 << ' ' << quoteName(filename.toFilesystemEncoding());
826 string const command_str = command.str();
828 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
830 cmd_ret const ret = runCommand(command_str);
831 if (ret.first != 0) {
832 Alert::error(_("Conversion script failed"),
833 bformat(_("%1$s is from a different version"
834 " of LyX, but the lyx2lyx script"
835 " failed to convert it."),
836 from_utf8(filename.absFilename())));
839 bool const ret = readFile(tmpfile);
840 // Do stuff with tmpfile name and buffer name here.
841 return ret ? success : failure;
846 if (readDocument(lex)) {
847 Alert::error(_("Document format failure"),
848 bformat(_("%1$s ended unexpectedly, which means"
849 " that it is probably corrupted."),
850 from_utf8(filename.absFilename())));
853 d->file_fully_loaded = true;
858 // Should probably be moved to somewhere else: BufferView? LyXView?
859 bool Buffer::save() const
861 // We don't need autosaves in the immediate future. (Asger)
862 resetAutosaveTimers();
864 string const encodedFilename = d->filename.toFilesystemEncoding();
867 bool madeBackup = false;
869 // make a backup if the file already exists
870 if (lyxrc.make_backup && fileName().exists()) {
871 backupName = FileName(absFileName() + '~');
872 if (!lyxrc.backupdir_path.empty()) {
873 string const mangledName =
874 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
875 backupName = FileName(addName(lyxrc.backupdir_path,
878 if (fileName().copyTo(backupName)) {
881 Alert::error(_("Backup failure"),
882 bformat(_("Cannot create backup file %1$s.\n"
883 "Please check whether the directory exists and is writeable."),
884 from_utf8(backupName.absFilename())));
885 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
889 // ask if the disk file has been externally modified (use checksum method)
890 if (fileName().exists() && isExternallyModified(checksum_method)) {
891 docstring const file = makeDisplayPath(absFileName(), 20);
892 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
893 "you want to overwrite this file?"), file);
894 int const ret = Alert::prompt(_("Overwrite modified file?"),
895 text, 1, 1, _("&Overwrite"), _("&Cancel"));
900 if (writeFile(d->filename)) {
904 // Saving failed, so backup is not backup
906 backupName.moveTo(d->filename);
912 bool Buffer::writeFile(FileName const & fname) const
914 if (d->read_only && fname == d->filename)
919 docstring const str = bformat(_("Saving document %1$s..."),
920 makeDisplayPath(fname.absFilename()));
923 if (params().compressed) {
924 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
925 retval = ofs && write(ofs);
927 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
928 retval = ofs && write(ofs);
932 message(str + _(" could not write file!"));
936 removeAutosaveFile();
938 saveCheckSum(d->filename);
939 message(str + _(" done."));
945 bool Buffer::write(ostream & ofs) const
948 // Use the standard "C" locale for file output.
949 ofs.imbue(locale::classic());
952 // The top of the file should not be written by params().
954 // write out a comment in the top of the file
955 ofs << "#LyX " << lyx_version
956 << " created this file. For more info see http://www.lyx.org/\n"
957 << "\\lyxformat " << LYX_FORMAT << "\n"
958 << "\\begin_document\n";
960 /// For each author, set 'used' to true if there is a change
961 /// by this author in the document; otherwise set it to 'false'.
962 AuthorList::Authors::const_iterator a_it = params().authors().begin();
963 AuthorList::Authors::const_iterator a_end = params().authors().end();
964 for (; a_it != a_end; ++a_it)
965 a_it->setUsed(false);
967 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
968 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
969 for ( ; it != end; ++it)
970 it->checkAuthors(params().authors());
972 // now write out the buffer parameters.
973 ofs << "\\begin_header\n";
974 params().writeFile(ofs);
975 ofs << "\\end_header\n";
978 ofs << "\n\\begin_body\n";
980 ofs << "\n\\end_body\n";
982 // Write marker that shows file is complete
983 ofs << "\\end_document" << endl;
985 // Shouldn't really be needed....
988 // how to check if close went ok?
989 // Following is an attempt... (BE 20001011)
991 // good() returns false if any error occured, including some
993 // bad() returns true if something bad happened in the buffer,
994 // which should include file system full errors.
999 lyxerr << "File was not closed properly." << endl;
1006 bool Buffer::makeLaTeXFile(FileName const & fname,
1007 string const & original_path,
1008 OutputParams const & runparams_in,
1009 bool output_preamble, bool output_body) const
1011 OutputParams runparams = runparams_in;
1012 if (params().useXetex)
1013 runparams.flavor = OutputParams::XETEX;
1015 string const encoding = runparams.encoding->iconvName();
1016 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1019 try { ofs.reset(encoding); }
1020 catch (iconv_codecvt_facet_exception & e) {
1021 lyxerr << "Caught iconv exception: " << e.what() << endl;
1022 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1023 "verify that the support software for your encoding (%1$s) is "
1024 "properly installed"), from_ascii(encoding)));
1027 if (!openFileWrite(ofs, fname))
1030 //TexStream ts(ofs.rdbuf(), &texrow());
1031 ErrorList & errorList = d->errorLists["Export"];
1033 bool failed_export = false;
1036 writeLaTeXSource(ofs, original_path,
1037 runparams, output_preamble, output_body);
1039 catch (EncodingException & e) {
1040 odocstringstream ods;
1041 ods.put(e.failed_char);
1043 oss << "0x" << hex << e.failed_char << dec;
1044 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1045 " (code point %2$s)"),
1046 ods.str(), from_utf8(oss.str()));
1047 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1048 "representable in the chosen encoding.\n"
1049 "Changing the document encoding to utf8 could help."),
1050 e.par_id, e.pos, e.pos + 1));
1051 failed_export = true;
1053 catch (iconv_codecvt_facet_exception & e) {
1054 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1055 _(e.what()), -1, 0, 0));
1056 failed_export = true;
1058 catch (exception const & e) {
1059 errorList.push_back(ErrorItem(_("conversion failed"),
1060 _(e.what()), -1, 0, 0));
1061 failed_export = true;
1064 lyxerr << "Caught some really weird exception..." << endl;
1070 failed_export = true;
1071 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1075 return !failed_export;
1079 void Buffer::writeLaTeXSource(odocstream & os,
1080 string const & original_path,
1081 OutputParams const & runparams_in,
1082 bool const output_preamble, bool const output_body) const
1084 // The child documents, if any, shall be already loaded at this point.
1086 OutputParams runparams = runparams_in;
1088 // Classify the unicode characters appearing in math insets
1089 Encodings::initUnicodeMath(*this);
1091 // validate the buffer.
1092 LYXERR(Debug::LATEX, " Validating buffer...");
1093 LaTeXFeatures features(*this, params(), runparams);
1095 LYXERR(Debug::LATEX, " Buffer validation done.");
1097 // The starting paragraph of the coming rows is the
1098 // first paragraph of the document. (Asger)
1099 if (output_preamble && runparams.nice) {
1100 os << "%% LyX " << lyx_version << " created this file. "
1101 "For more info, see http://www.lyx.org/.\n"
1102 "%% Do not edit unless you really know what "
1104 d->texrow.newline();
1105 d->texrow.newline();
1107 LYXERR(Debug::INFO, "lyx document header finished");
1109 // Don't move this behind the parent_buffer=0 code below,
1110 // because then the macros will not get the right "redefinition"
1111 // flag as they don't see the parent macros which are output before.
1114 // fold macros if possible, still with parent buffer as the
1115 // macros will be put in the prefix anyway.
1116 updateMacroInstances();
1118 // There are a few differences between nice LaTeX and usual files:
1119 // usual is \batchmode and has a
1120 // special input@path to allow the including of figures
1121 // with either \input or \includegraphics (what figinsets do).
1122 // input@path is set when the actual parameter
1123 // original_path is set. This is done for usual tex-file, but not
1124 // for nice-latex-file. (Matthias 250696)
1125 // Note that input@path is only needed for something the user does
1126 // in the preamble, included .tex files or ERT, files included by
1127 // LyX work without it.
1128 if (output_preamble) {
1129 if (!runparams.nice) {
1130 // code for usual, NOT nice-latex-file
1131 os << "\\batchmode\n"; // changed
1132 // from \nonstopmode
1133 d->texrow.newline();
1135 if (!original_path.empty()) {
1137 // We don't know the encoding of inputpath
1138 docstring const inputpath = from_utf8(latex_path(original_path));
1139 os << "\\makeatletter\n"
1140 << "\\def\\input@path{{"
1141 << inputpath << "/}}\n"
1142 << "\\makeatother\n";
1143 d->texrow.newline();
1144 d->texrow.newline();
1145 d->texrow.newline();
1148 // get parent macros (if this buffer has a parent) which will be
1149 // written at the document begin further down.
1150 MacroSet parentMacros;
1151 listParentMacros(parentMacros, features);
1153 // Write the preamble
1154 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1156 runparams.use_japanese = features.isRequired("japanese");
1162 os << "\\begin{document}\n";
1163 d->texrow.newline();
1165 // output the parent macros
1166 MacroSet::iterator it = parentMacros.begin();
1167 MacroSet::iterator end = parentMacros.end();
1168 for (; it != end; ++it)
1169 (*it)->write(os, true);
1170 } // output_preamble
1172 d->texrow.start(paragraphs().begin()->id(), 0);
1174 LYXERR(Debug::INFO, "preamble finished, now the body.");
1176 // if we are doing a real file with body, even if this is the
1177 // child of some other buffer, let's cut the link here.
1178 // This happens for example if only a child document is printed.
1179 Buffer const * save_parent = 0;
1180 if (output_preamble) {
1181 save_parent = d->parent();
1186 latexParagraphs(*this, text(), os, d->texrow, runparams);
1188 // Restore the parenthood if needed
1189 if (output_preamble)
1190 d->setParent(save_parent);
1192 // add this just in case after all the paragraphs
1194 d->texrow.newline();
1196 if (output_preamble) {
1197 os << "\\end{document}\n";
1198 d->texrow.newline();
1199 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1201 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1203 runparams_in.encoding = runparams.encoding;
1205 // Just to be sure. (Asger)
1206 d->texrow.newline();
1208 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1209 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1213 bool Buffer::isLatex() const
1215 return params().documentClass().outputType() == LATEX;
1219 bool Buffer::isLiterate() const
1221 return params().documentClass().outputType() == LITERATE;
1225 bool Buffer::isDocBook() const
1227 return params().documentClass().outputType() == DOCBOOK;
1231 void Buffer::makeDocBookFile(FileName const & fname,
1232 OutputParams const & runparams,
1233 bool const body_only) const
1235 LYXERR(Debug::LATEX, "makeDocBookFile...");
1238 if (!openFileWrite(ofs, fname))
1241 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1245 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1249 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1250 OutputParams const & runparams,
1251 bool const only_body) const
1253 LaTeXFeatures features(*this, params(), runparams);
1258 DocumentClass const & tclass = params().documentClass();
1259 string const top_element = tclass.latexname();
1262 if (runparams.flavor == OutputParams::XML)
1263 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1266 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1269 if (! tclass.class_header().empty())
1270 os << from_ascii(tclass.class_header());
1271 else if (runparams.flavor == OutputParams::XML)
1272 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1273 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1275 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1277 docstring preamble = from_utf8(params().preamble);
1278 if (runparams.flavor != OutputParams::XML ) {
1279 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1280 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1281 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1282 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1285 string const name = runparams.nice
1286 ? changeExtension(absFileName(), ".sgml") : fname;
1287 preamble += features.getIncludedFiles(name);
1288 preamble += features.getLyXSGMLEntities();
1290 if (!preamble.empty()) {
1291 os << "\n [ " << preamble << " ]";
1296 string top = top_element;
1298 if (runparams.flavor == OutputParams::XML)
1299 top += params().language->code();
1301 top += params().language->code().substr(0, 2);
1304 if (!params().options.empty()) {
1306 top += params().options;
1309 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1310 << " file was created by LyX " << lyx_version
1311 << "\n See http://www.lyx.org/ for more information -->\n";
1313 params().documentClass().counters().reset();
1317 sgml::openTag(os, top);
1319 docbookParagraphs(text(), *this, os, runparams);
1320 sgml::closeTag(os, top_element);
1324 void Buffer::makeLyXHTMLFile(FileName const & fname,
1325 OutputParams const & runparams,
1326 bool const body_only) const
1328 LYXERR(Debug::LATEX, "makeLYXHTMLFile...");
1331 if (!openFileWrite(ofs, fname))
1334 writeLyXHTMLSource(ofs, runparams, body_only);
1338 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1342 void Buffer::writeLyXHTMLSource(odocstream & os,
1343 OutputParams const & runparams,
1344 bool const only_body) const
1346 LaTeXFeatures features(*this, params(), runparams);
1352 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" <<
1353 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1354 // FIXME Language should be set properly.
1355 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
1358 // FIXME Presumably need to set this right
1359 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1360 // FIXME Get this during validation? What about other meta-data?
1361 os << "<title>TBA</title>\n";
1363 os << features.getTClassHTMLPreamble();
1367 docstring const styleinfo = features.getTClassHTMLStyles();
1368 if (!styleinfo.empty()) {
1369 os << "<style type='text/css'>\n";
1373 os << "</head>\n<body>\n";
1376 params().documentClass().counters().reset();
1377 xhtmlParagraphs(text(), *this, os, runparams);
1379 os << "</body>\n</html>\n";
1383 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1384 // Other flags: -wall -v0 -x
1385 int Buffer::runChktex()
1389 // get LaTeX-Filename
1390 FileName const path(temppath());
1391 string const name = addName(path.absFilename(), latexName());
1392 string const org_path = filePath();
1394 PathChanger p(path); // path to LaTeX file
1395 message(_("Running chktex..."));
1397 // Generate the LaTeX file if neccessary
1398 OutputParams runparams(¶ms().encoding());
1399 runparams.flavor = OutputParams::LATEX;
1400 runparams.nice = false;
1401 makeLaTeXFile(FileName(name), org_path, runparams);
1404 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1405 int const res = chktex.run(terr); // run chktex
1408 Alert::error(_("chktex failure"),
1409 _("Could not run chktex successfully."));
1410 } else if (res > 0) {
1411 ErrorList & errlist = d->errorLists["ChkTeX"];
1413 bufferErrors(terr, errlist);
1424 void Buffer::validate(LaTeXFeatures & features) const
1426 params().validate(features);
1430 for_each(paragraphs().begin(), paragraphs().end(),
1431 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1433 if (lyxerr.debugging(Debug::LATEX)) {
1434 features.showStruct();
1439 void Buffer::getLabelList(vector<docstring> & list) const
1441 // If this is a child document, use the parent's list instead.
1442 Buffer const * const pbuf = d->parent();
1444 pbuf->getLabelList(list);
1449 Toc & toc = d->toc_backend.toc("label");
1450 TocIterator toc_it = toc.begin();
1451 TocIterator end = toc.end();
1452 for (; toc_it != end; ++toc_it) {
1453 if (toc_it->depth() == 0)
1454 list.push_back(toc_it->str());
1459 void Buffer::updateBibfilesCache(UpdateScope scope) const
1461 // If this is a child document, use the parent's cache instead.
1462 Buffer const * const pbuf = d->parent();
1463 if (pbuf && scope != UpdateChildOnly) {
1464 pbuf->updateBibfilesCache();
1468 d->bibfilesCache_.clear();
1469 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1470 if (it->lyxCode() == BIBTEX_CODE) {
1471 InsetBibtex const & inset =
1472 static_cast<InsetBibtex const &>(*it);
1473 support::FileNameList const bibfiles = inset.getBibFiles();
1474 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1477 } else if (it->lyxCode() == INCLUDE_CODE) {
1478 InsetInclude & inset =
1479 static_cast<InsetInclude &>(*it);
1480 inset.updateBibfilesCache();
1481 support::FileNameList const & bibfiles =
1482 inset.getBibfilesCache();
1483 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1488 // the bibinfo cache is now invalid
1489 d->bibinfoCacheValid_ = false;
1493 void Buffer::invalidateBibinfoCache()
1495 d->bibinfoCacheValid_ = false;
1499 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1501 // If this is a child document, use the parent's cache instead.
1502 Buffer const * const pbuf = d->parent();
1503 if (pbuf && scope != UpdateChildOnly)
1504 return pbuf->getBibfilesCache();
1506 // We update the cache when first used instead of at loading time.
1507 if (d->bibfilesCache_.empty())
1508 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1510 return d->bibfilesCache_;
1514 BiblioInfo const & Buffer::masterBibInfo() const
1516 // if this is a child document and the parent is already loaded
1517 // use the parent's list instead [ale990412]
1518 Buffer const * const tmp = masterBuffer();
1521 return tmp->masterBibInfo();
1522 return localBibInfo();
1526 BiblioInfo const & Buffer::localBibInfo() const
1528 if (d->bibinfoCacheValid_) {
1529 support::FileNameList const & bibfilesCache = getBibfilesCache();
1530 // compare the cached timestamps with the actual ones.
1531 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1532 support::FileNameList::const_iterator en = bibfilesCache.end();
1533 for (; ei != en; ++ ei) {
1534 time_t lastw = ei->lastModified();
1535 if (lastw != d->bibfileStatus_[*ei]) {
1536 d->bibinfoCacheValid_ = false;
1537 d->bibfileStatus_[*ei] = lastw;
1543 if (!d->bibinfoCacheValid_) {
1544 d->bibinfo_.clear();
1545 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1546 it->fillWithBibKeys(d->bibinfo_, it);
1547 d->bibinfoCacheValid_ = true;
1553 bool Buffer::isDepClean(string const & name) const
1555 DepClean::const_iterator const it = d->dep_clean.find(name);
1556 if (it == d->dep_clean.end())
1562 void Buffer::markDepClean(string const & name)
1564 d->dep_clean[name] = true;
1568 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1570 switch (cmd.action) {
1571 case LFUN_BUFFER_EXPORT: {
1572 docstring const arg = cmd.argument();
1573 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1575 flag.message(bformat(
1576 _("Don't know how to export to format: %1$s"), arg));
1577 flag.setEnabled(enable);
1581 case LFUN_BRANCH_ACTIVATE:
1582 case LFUN_BRANCH_DEACTIVATE: {
1583 BranchList const & branchList = params().branchlist();
1584 docstring const branchName = cmd.argument();
1585 flag.setEnabled(!branchName.empty()
1586 && branchList.find(branchName));
1590 case LFUN_BRANCH_ADD:
1591 case LFUN_BRANCHES_RENAME:
1592 case LFUN_BUFFER_PRINT:
1593 // if no Buffer is present, then of course we won't be called!
1594 flag.setEnabled(true);
1604 void Buffer::dispatch(string const & command, DispatchResult & result)
1606 return dispatch(lyxaction.lookupFunc(command), result);
1610 // NOTE We can end up here even if we have no GUI, because we are called
1611 // by LyX::exec to handled command-line requests. So we may need to check
1612 // whether we have a GUI or not. The boolean use_gui holds this information.
1613 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1615 // We'll set this back to false if need be.
1616 bool dispatched = true;
1618 switch (func.action) {
1619 case LFUN_BUFFER_EXPORT: {
1620 bool success = doExport(to_utf8(func.argument()), false);
1621 dr.setError(success);
1623 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1628 case LFUN_BRANCH_ADD: {
1629 BranchList & branchList = params().branchlist();
1630 docstring const branchName = func.argument();
1631 if (branchName.empty()) {
1635 Branch * branch = branchList.find(branchName);
1637 LYXERR0("Branch " << branchName << " does already exist.");
1639 docstring const msg =
1640 bformat(_("Branch \"%1$s\" does already exist."), branchName);
1643 branchList.add(branchName);
1645 dr.update(Update::Force);
1650 case LFUN_BRANCH_ACTIVATE:
1651 case LFUN_BRANCH_DEACTIVATE: {
1652 BranchList & branchList = params().branchlist();
1653 docstring const branchName = func.argument();
1654 // the case without a branch name is handled elsewhere
1655 if (branchName.empty()) {
1659 Branch * branch = branchList.find(branchName);
1661 LYXERR0("Branch " << branchName << " does not exist.");
1663 docstring const msg =
1664 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1667 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1669 dr.update(Update::Force);
1674 case LFUN_BRANCHES_RENAME: {
1675 if (func.argument().empty())
1678 docstring const oldname = from_utf8(func.getArg(0));
1679 docstring const newname = from_utf8(func.getArg(1));
1680 InsetIterator it = inset_iterator_begin(inset());
1681 InsetIterator const end = inset_iterator_end(inset());
1682 bool success = false;
1683 for (; it != end; ++it) {
1684 if (it->lyxCode() == BRANCH_CODE) {
1685 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1686 if (ins.branch() == oldname) {
1687 undo().recordUndo(it);
1688 ins.rename(newname);
1693 if (it->lyxCode() == INCLUDE_CODE) {
1694 // get buffer of external file
1695 InsetInclude const & ins =
1696 static_cast<InsetInclude const &>(*it);
1697 Buffer * child = ins.getChildBuffer();
1700 child->dispatch(func, dr);
1705 dr.update(Update::Force);
1709 case LFUN_BUFFER_PRINT: {
1710 // we'll assume there's a problem until we succeed
1712 string target = func.getArg(0);
1713 string target_name = func.getArg(1);
1714 string command = func.getArg(2);
1717 || target_name.empty()
1718 || command.empty()) {
1719 LYXERR0("Unable to parse " << func.argument());
1720 docstring const msg =
1721 bformat(_("Unable to parse \"%1$s\""), func.argument());
1725 if (target != "printer" && target != "file") {
1726 LYXERR0("Unrecognized target \"" << target << '"');
1727 docstring const msg =
1728 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1733 if (!doExport("dvi", true)) {
1734 showPrintError(absFileName());
1735 dr.setMessage(_("Error exporting to DVI."));
1739 // Push directory path.
1740 string const path = temppath();
1741 // Prevent the compiler from optimizing away p
1745 // there are three cases here:
1746 // 1. we print to a file
1747 // 2. we print directly to a printer
1748 // 3. we print using a spool command (print to file first)
1751 string const dviname = changeExtension(latexName(true), "dvi");
1753 if (target == "printer") {
1754 if (!lyxrc.print_spool_command.empty()) {
1755 // case 3: print using a spool
1756 string const psname = changeExtension(dviname,".ps");
1757 command += ' ' + lyxrc.print_to_file
1760 + quoteName(dviname);
1762 string command2 = lyxrc.print_spool_command + ' ';
1763 if (target_name != "default") {
1764 command2 += lyxrc.print_spool_printerprefix
1768 command2 += quoteName(psname);
1770 // If successful, then spool command
1771 res = one.startscript(Systemcall::Wait, command);
1774 // If there's no GUI, we have to wait on this command. Otherwise,
1775 // LyX deletes the temporary directory, and with it the spooled
1776 // file, before it can be printed!!
1777 Systemcall::Starttype stype = use_gui ?
1778 Systemcall::DontWait : Systemcall::Wait;
1779 res = one.startscript(stype, command2);
1782 // case 2: print directly to a printer
1783 if (target_name != "default")
1784 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1786 Systemcall::Starttype stype = use_gui ?
1787 Systemcall::DontWait : Systemcall::Wait;
1788 res = one.startscript(stype, command + quoteName(dviname));
1792 // case 1: print to a file
1793 FileName const filename(makeAbsPath(target_name, filePath()));
1794 FileName const dvifile(makeAbsPath(dviname, path));
1795 if (filename.exists()) {
1796 docstring text = bformat(
1797 _("The file %1$s already exists.\n\n"
1798 "Do you want to overwrite that file?"),
1799 makeDisplayPath(filename.absFilename()));
1800 if (Alert::prompt(_("Overwrite file?"),
1801 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1804 command += ' ' + lyxrc.print_to_file
1805 + quoteName(filename.toFilesystemEncoding())
1807 + quoteName(dvifile.toFilesystemEncoding());
1809 Systemcall::Starttype stype = use_gui ?
1810 Systemcall::DontWait : Systemcall::Wait;
1811 res = one.startscript(stype, command);
1817 dr.setMessage(_("Error running external commands."));
1818 showPrintError(absFileName());
1827 dr.dispatched(dispatched);
1831 void Buffer::changeLanguage(Language const * from, Language const * to)
1833 LASSERT(from, /**/);
1836 for_each(par_iterator_begin(),
1838 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1842 bool Buffer::isMultiLingual() const
1844 ParConstIterator end = par_iterator_end();
1845 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1846 if (it->isMultiLingual(params()))
1853 DocIterator Buffer::getParFromID(int const id) const
1855 Buffer * buf = const_cast<Buffer *>(this);
1857 // John says this is called with id == -1 from undo
1858 lyxerr << "getParFromID(), id: " << id << endl;
1859 return doc_iterator_end(buf);
1862 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1863 if (it.paragraph().id() == id)
1866 return doc_iterator_end(buf);
1870 bool Buffer::hasParWithID(int const id) const
1872 return !getParFromID(id).atEnd();
1876 ParIterator Buffer::par_iterator_begin()
1878 return ParIterator(doc_iterator_begin(this));
1882 ParIterator Buffer::par_iterator_end()
1884 return ParIterator(doc_iterator_end(this));
1888 ParConstIterator Buffer::par_iterator_begin() const
1890 return ParConstIterator(doc_iterator_begin(this));
1894 ParConstIterator Buffer::par_iterator_end() const
1896 return ParConstIterator(doc_iterator_end(this));
1900 Language const * Buffer::language() const
1902 return params().language;
1906 docstring const Buffer::B_(string const & l10n) const
1908 return params().B_(l10n);
1912 bool Buffer::isClean() const
1914 return d->lyx_clean;
1918 bool Buffer::isBakClean() const
1920 return d->bak_clean;
1924 bool Buffer::isExternallyModified(CheckMethod method) const
1926 LASSERT(d->filename.exists(), /**/);
1927 // if method == timestamp, check timestamp before checksum
1928 return (method == checksum_method
1929 || d->timestamp_ != d->filename.lastModified())
1930 && d->checksum_ != d->filename.checksum();
1934 void Buffer::saveCheckSum(FileName const & file) const
1936 if (file.exists()) {
1937 d->timestamp_ = file.lastModified();
1938 d->checksum_ = file.checksum();
1940 // in the case of save to a new file.
1947 void Buffer::markClean() const
1949 if (!d->lyx_clean) {
1950 d->lyx_clean = true;
1953 // if the .lyx file has been saved, we don't need an
1955 d->bak_clean = true;
1959 void Buffer::markBakClean() const
1961 d->bak_clean = true;
1965 void Buffer::setUnnamed(bool flag)
1971 bool Buffer::isUnnamed() const
1977 // FIXME: this function should be moved to buffer_pimpl.C
1978 void Buffer::markDirty()
1981 d->lyx_clean = false;
1984 d->bak_clean = false;
1986 DepClean::iterator it = d->dep_clean.begin();
1987 DepClean::const_iterator const end = d->dep_clean.end();
1989 for (; it != end; ++it)
1994 FileName Buffer::fileName() const
2000 string Buffer::absFileName() const
2002 return d->filename.absFilename();
2006 string Buffer::filePath() const
2008 return d->filename.onlyPath().absFilename() + "/";
2012 bool Buffer::isReadonly() const
2014 return d->read_only;
2018 void Buffer::setParent(Buffer const * buffer)
2020 // Avoids recursive include.
2021 d->setParent(buffer == this ? 0 : buffer);
2026 Buffer const * Buffer::parent() const
2032 void Buffer::collectRelatives(BufferSet & bufs) const
2036 parent()->collectRelatives(bufs);
2038 // loop over children
2039 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2040 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2041 for (; it != end; ++it)
2042 bufs.insert(const_cast<Buffer *>(it->first));
2046 std::vector<Buffer const *> Buffer::allRelatives() const
2049 collectRelatives(bufs);
2050 BufferSet::iterator it = bufs.begin();
2051 std::vector<Buffer const *> ret;
2052 for (; it != bufs.end(); ++it)
2058 Buffer const * Buffer::masterBuffer() const
2060 Buffer const * const pbuf = d->parent();
2064 return pbuf->masterBuffer();
2068 bool Buffer::isChild(Buffer * child) const
2070 return d->children_positions.find(child) != d->children_positions.end();
2074 DocIterator Buffer::firstChildPosition(Buffer const * child)
2076 Impl::BufferPositionMap::iterator it;
2077 it = d->children_positions.find(child);
2078 if (it == d->children_positions.end())
2079 return DocIterator(this);
2084 std::vector<Buffer *> Buffer::getChildren() const
2086 std::vector<Buffer *> clist;
2087 // loop over children
2088 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2089 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2090 for (; it != end; ++it) {
2091 Buffer * child = const_cast<Buffer *>(it->first);
2092 clist.push_back(child);
2093 // there might be grandchildren
2094 std::vector<Buffer *> glist = child->getChildren();
2095 for (vector<Buffer *>::const_iterator git = glist.begin();
2096 git != glist.end(); ++git)
2097 clist.push_back(*git);
2103 template<typename M>
2104 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2109 typename M::iterator it = m.lower_bound(x);
2110 if (it == m.begin())
2118 MacroData const * Buffer::getBufferMacro(docstring const & name,
2119 DocIterator const & pos) const
2121 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2123 // if paragraphs have no macro context set, pos will be empty
2127 // we haven't found anything yet
2128 DocIterator bestPos = par_iterator_begin();
2129 MacroData const * bestData = 0;
2131 // find macro definitions for name
2132 Impl::NamePositionScopeMacroMap::iterator nameIt
2133 = d->macros.find(name);
2134 if (nameIt != d->macros.end()) {
2135 // find last definition in front of pos or at pos itself
2136 Impl::PositionScopeMacroMap::const_iterator it
2137 = greatest_below(nameIt->second, pos);
2138 if (it != nameIt->second.end()) {
2140 // scope ends behind pos?
2141 if (pos < it->second.first) {
2142 // Looks good, remember this. If there
2143 // is no external macro behind this,
2144 // we found the right one already.
2145 bestPos = it->first;
2146 bestData = &it->second.second;
2150 // try previous macro if there is one
2151 if (it == nameIt->second.begin())
2158 // find macros in included files
2159 Impl::PositionScopeBufferMap::const_iterator it
2160 = greatest_below(d->position_to_children, pos);
2161 if (it == d->position_to_children.end())
2162 // no children before
2166 // do we know something better (i.e. later) already?
2167 if (it->first < bestPos )
2170 // scope ends behind pos?
2171 if (pos < it->second.first) {
2172 // look for macro in external file
2173 d->macro_lock = true;
2174 MacroData const * data
2175 = it->second.second->getMacro(name, false);
2176 d->macro_lock = false;
2178 bestPos = it->first;
2184 // try previous file if there is one
2185 if (it == d->position_to_children.begin())
2190 // return the best macro we have found
2195 MacroData const * Buffer::getMacro(docstring const & name,
2196 DocIterator const & pos, bool global) const
2201 // query buffer macros
2202 MacroData const * data = getBufferMacro(name, pos);
2206 // If there is a master buffer, query that
2207 Buffer const * const pbuf = d->parent();
2209 d->macro_lock = true;
2210 MacroData const * macro = pbuf->getMacro(
2211 name, *this, false);
2212 d->macro_lock = false;
2218 data = MacroTable::globalMacros().get(name);
2227 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2229 // set scope end behind the last paragraph
2230 DocIterator scope = par_iterator_begin();
2231 scope.pit() = scope.lastpit() + 1;
2233 return getMacro(name, scope, global);
2237 MacroData const * Buffer::getMacro(docstring const & name,
2238 Buffer const & child, bool global) const
2240 // look where the child buffer is included first
2241 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2242 if (it == d->children_positions.end())
2245 // check for macros at the inclusion position
2246 return getMacro(name, it->second, global);
2250 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2252 pit_type lastpit = it.lastpit();
2254 // look for macros in each paragraph
2255 while (it.pit() <= lastpit) {
2256 Paragraph & par = it.paragraph();
2258 // iterate over the insets of the current paragraph
2259 InsetList const & insets = par.insetList();
2260 InsetList::const_iterator iit = insets.begin();
2261 InsetList::const_iterator end = insets.end();
2262 for (; iit != end; ++iit) {
2263 it.pos() = iit->pos;
2265 // is it a nested text inset?
2266 if (iit->inset->asInsetText()) {
2267 // Inset needs its own scope?
2268 InsetText const * itext = iit->inset->asInsetText();
2269 bool newScope = itext->isMacroScope();
2271 // scope which ends just behind the inset
2272 DocIterator insetScope = it;
2275 // collect macros in inset
2276 it.push_back(CursorSlice(*iit->inset));
2277 updateMacros(it, newScope ? insetScope : scope);
2282 // is it an external file?
2283 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2284 // get buffer of external file
2285 InsetInclude const & inset =
2286 static_cast<InsetInclude const &>(*iit->inset);
2287 d->macro_lock = true;
2288 Buffer * child = inset.getChildBuffer();
2289 d->macro_lock = false;
2293 // register its position, but only when it is
2294 // included first in the buffer
2295 if (d->children_positions.find(child) ==
2296 d->children_positions.end())
2297 d->children_positions[child] = it;
2299 // register child with its scope
2300 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2304 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2308 MathMacroTemplate & macroTemplate =
2309 static_cast<MathMacroTemplate &>(*iit->inset);
2310 MacroContext mc(*this, it);
2311 macroTemplate.updateToContext(mc);
2314 bool valid = macroTemplate.validMacro();
2315 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2316 // then the BufferView's cursor will be invalid in
2317 // some cases which leads to crashes.
2322 d->macros[macroTemplate.name()][it] =
2323 Impl::ScopeMacro(scope, MacroData(*this, it));
2333 void Buffer::updateMacros() const
2338 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2340 // start with empty table
2342 d->children_positions.clear();
2343 d->position_to_children.clear();
2345 // Iterate over buffer, starting with first paragraph
2346 // The scope must be bigger than any lookup DocIterator
2347 // later. For the global lookup, lastpit+1 is used, hence
2348 // we use lastpit+2 here.
2349 DocIterator it = par_iterator_begin();
2350 DocIterator outerScope = it;
2351 outerScope.pit() = outerScope.lastpit() + 2;
2352 updateMacros(it, outerScope);
2356 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2358 InsetIterator it = inset_iterator_begin(inset());
2359 InsetIterator const end = inset_iterator_end(inset());
2360 for (; it != end; ++it) {
2361 if (it->lyxCode() == BRANCH_CODE) {
2362 InsetBranch & br = static_cast<InsetBranch &>(*it);
2363 docstring const name = br.branch();
2364 if (!from_master && !params().branchlist().find(name))
2365 result.push_back(name);
2366 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2367 result.push_back(name);
2370 if (it->lyxCode() == INCLUDE_CODE) {
2371 // get buffer of external file
2372 InsetInclude const & ins =
2373 static_cast<InsetInclude const &>(*it);
2374 Buffer * child = ins.getChildBuffer();
2377 child->getUsedBranches(result, true);
2380 // remove duplicates
2385 void Buffer::updateMacroInstances() const
2387 LYXERR(Debug::MACROS, "updateMacroInstances for "
2388 << d->filename.onlyFileName());
2389 DocIterator it = doc_iterator_begin(this);
2390 DocIterator end = doc_iterator_end(this);
2391 for (; it != end; it.forwardPos()) {
2392 // look for MathData cells in InsetMathNest insets
2393 Inset * inset = it.nextInset();
2397 InsetMath * minset = inset->asInsetMath();
2401 // update macro in all cells of the InsetMathNest
2402 DocIterator::idx_type n = minset->nargs();
2403 MacroContext mc = MacroContext(*this, it);
2404 for (DocIterator::idx_type i = 0; i < n; ++i) {
2405 MathData & data = minset->cell(i);
2406 data.updateMacros(0, mc);
2412 void Buffer::listMacroNames(MacroNameSet & macros) const
2417 d->macro_lock = true;
2419 // loop over macro names
2420 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2421 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2422 for (; nameIt != nameEnd; ++nameIt)
2423 macros.insert(nameIt->first);
2425 // loop over children
2426 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2427 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2428 for (; it != end; ++it)
2429 it->first->listMacroNames(macros);
2432 Buffer const * const pbuf = d->parent();
2434 pbuf->listMacroNames(macros);
2436 d->macro_lock = false;
2440 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2442 Buffer const * const pbuf = d->parent();
2447 pbuf->listMacroNames(names);
2450 MacroNameSet::iterator it = names.begin();
2451 MacroNameSet::iterator end = names.end();
2452 for (; it != end; ++it) {
2454 MacroData const * data =
2455 pbuf->getMacro(*it, *this, false);
2457 macros.insert(data);
2459 // we cannot access the original MathMacroTemplate anymore
2460 // here to calls validate method. So we do its work here manually.
2461 // FIXME: somehow make the template accessible here.
2462 if (data->optionals() > 0)
2463 features.require("xargs");
2469 Buffer::References & Buffer::references(docstring const & label)
2472 return const_cast<Buffer *>(masterBuffer())->references(label);
2474 RefCache::iterator it = d->ref_cache_.find(label);
2475 if (it != d->ref_cache_.end())
2476 return it->second.second;
2478 static InsetLabel const * dummy_il = 0;
2479 static References const dummy_refs;
2480 it = d->ref_cache_.insert(
2481 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2482 return it->second.second;
2486 Buffer::References const & Buffer::references(docstring const & label) const
2488 return const_cast<Buffer *>(this)->references(label);
2492 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2494 masterBuffer()->d->ref_cache_[label].first = il;
2498 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2500 return masterBuffer()->d->ref_cache_[label].first;
2504 void Buffer::clearReferenceCache() const
2507 d->ref_cache_.clear();
2511 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2514 //FIXME: This does not work for child documents yet.
2515 LASSERT(code == CITE_CODE, /**/);
2516 // Check if the label 'from' appears more than once
2517 vector<docstring> labels;
2519 BiblioInfo const & keys = masterBibInfo();
2520 BiblioInfo::const_iterator bit = keys.begin();
2521 BiblioInfo::const_iterator bend = keys.end();
2523 for (; bit != bend; ++bit)
2525 labels.push_back(bit->first);
2528 if (count(labels.begin(), labels.end(), from) > 1)
2531 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2532 if (it->lyxCode() == code) {
2533 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2534 docstring const oldValue = inset.getParam(paramName);
2535 if (oldValue == from)
2536 inset.setParam(paramName, to);
2542 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2543 pit_type par_end, bool full_source) const
2545 OutputParams runparams(¶ms().encoding());
2546 runparams.nice = true;
2547 runparams.flavor = params().useXetex ?
2548 OutputParams::XETEX : OutputParams::LATEX;
2549 runparams.linelen = lyxrc.plaintext_linelen;
2550 // No side effect of file copying and image conversion
2551 runparams.dryrun = true;
2554 os << "% " << _("Preview source code") << "\n\n";
2556 d->texrow.newline();
2557 d->texrow.newline();
2559 writeDocBookSource(os, absFileName(), runparams, false);
2561 // latex or literate
2562 writeLaTeXSource(os, string(), runparams, true, true);
2564 runparams.par_begin = par_begin;
2565 runparams.par_end = par_end;
2566 if (par_begin + 1 == par_end) {
2568 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2572 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2573 convert<docstring>(par_begin),
2574 convert<docstring>(par_end - 1))
2581 // output paragraphs
2583 docbookParagraphs(text(), *this, os, runparams);
2585 // latex or literate
2586 latexParagraphs(*this, text(), os, texrow, runparams);
2591 ErrorList & Buffer::errorList(string const & type) const
2593 static ErrorList emptyErrorList;
2594 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2595 if (I == d->errorLists.end())
2596 return emptyErrorList;
2602 void Buffer::updateTocItem(std::string const & type,
2603 DocIterator const & dit) const
2606 gui_->updateTocItem(type, dit);
2610 void Buffer::structureChanged() const
2613 gui_->structureChanged();
2617 void Buffer::errors(string const & err, bool from_master) const
2620 gui_->errors(err, from_master);
2624 void Buffer::message(docstring const & msg) const
2631 void Buffer::setBusy(bool on) const
2638 void Buffer::setReadOnly(bool on) const
2641 d->wa_->setReadOnly(on);
2645 void Buffer::updateTitles() const
2648 d->wa_->updateTitles();
2652 void Buffer::resetAutosaveTimers() const
2655 gui_->resetAutosaveTimers();
2659 bool Buffer::hasGuiDelegate() const
2665 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2674 class AutoSaveBuffer : public ForkedProcess {
2677 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2678 : buffer_(buffer), fname_(fname) {}
2680 virtual boost::shared_ptr<ForkedProcess> clone() const
2682 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2687 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2688 from_utf8(fname_.absFilename())));
2689 return run(DontWait);
2693 virtual int generateChild();
2695 Buffer const & buffer_;
2700 int AutoSaveBuffer::generateChild()
2702 // tmp_ret will be located (usually) in /tmp
2703 // will that be a problem?
2704 // Note that this calls ForkedCalls::fork(), so it's
2705 // ok cross-platform.
2706 pid_t const pid = fork();
2707 // If you want to debug the autosave
2708 // you should set pid to -1, and comment out the fork.
2709 if (pid != 0 && pid != -1)
2712 // pid = -1 signifies that lyx was unable
2713 // to fork. But we will do the save
2715 bool failed = false;
2716 FileName const tmp_ret = FileName::tempName("lyxauto");
2717 if (!tmp_ret.empty()) {
2718 buffer_.writeFile(tmp_ret);
2719 // assume successful write of tmp_ret
2720 if (!tmp_ret.moveTo(fname_))
2726 // failed to write/rename tmp_ret so try writing direct
2727 if (!buffer_.writeFile(fname_)) {
2728 // It is dangerous to do this in the child,
2729 // but safe in the parent, so...
2730 if (pid == -1) // emit message signal.
2731 buffer_.message(_("Autosave failed!"));
2735 if (pid == 0) // we are the child so...
2744 FileName Buffer::getAutosaveFilename() const
2746 // if the document is unnamed try to save in the backup dir, else
2747 // in the default document path, and as a last try in the filePath,
2748 // which will most often be the temporary directory
2751 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2752 : lyxrc.backupdir_path;
2753 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2756 string const fname = "#" + d->filename.onlyFileName() + "#";
2757 return makeAbsPath(fname, fpath);
2761 void Buffer::removeAutosaveFile() const
2763 FileName const f = getAutosaveFilename();
2769 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2771 FileName const newauto = getAutosaveFilename();
2772 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2773 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2777 // Perfect target for a thread...
2778 void Buffer::autoSave() const
2780 if (isBakClean() || isReadonly()) {
2781 // We don't save now, but we'll try again later
2782 resetAutosaveTimers();
2786 // emit message signal.
2787 message(_("Autosaving current document..."));
2788 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2792 resetAutosaveTimers();
2796 string Buffer::bufferFormat() const
2798 string format = params().documentClass().outputFormat();
2799 if (format == "latex") {
2800 if (params().useXetex)
2802 if (params().encoding().package() == Encoding::japanese)
2809 string Buffer::getDefaultOutputFormat() const
2811 if (!params().defaultOutputFormat.empty()
2812 && params().defaultOutputFormat != "default")
2813 return params().defaultOutputFormat;
2814 typedef vector<Format const *> Formats;
2815 Formats formats = exportableFormats(true);
2818 || params().useXetex
2819 || params().encoding().package() == Encoding::japanese) {
2820 if (formats.empty())
2822 // return the first we find
2823 return formats.front()->name();
2825 return lyxrc.default_view_format;
2830 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2831 string & result_file) const
2833 string backend_format;
2834 OutputParams runparams(¶ms().encoding());
2835 runparams.flavor = OutputParams::LATEX;
2836 runparams.linelen = lyxrc.plaintext_linelen;
2837 vector<string> backs = backends();
2838 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2839 // Get shortest path to format
2840 Graph::EdgePath path;
2841 for (vector<string>::const_iterator it = backs.begin();
2842 it != backs.end(); ++it) {
2843 Graph::EdgePath p = theConverters().getPath(*it, format);
2844 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2845 backend_format = *it;
2850 runparams.flavor = theConverters().getFlavor(path);
2852 Alert::error(_("Couldn't export file"),
2853 bformat(_("No information for exporting the format %1$s."),
2854 formats.prettyName(format)));
2858 backend_format = format;
2859 // FIXME: Don't hardcode format names here, but use a flag
2860 if (backend_format == "pdflatex")
2861 runparams.flavor = OutputParams::PDFLATEX;
2864 string filename = latexName(false);
2865 filename = addName(temppath(), filename);
2866 filename = changeExtension(filename,
2867 formats.extension(backend_format));
2870 updateMacroInstances();
2872 // Plain text backend
2873 if (backend_format == "text")
2874 writePlaintextFile(*this, FileName(filename), runparams);
2876 else if (backend_format == "xhtml")
2877 makeLyXHTMLFile(FileName(filename), runparams);
2878 else if (backend_format == "lyx")
2879 writeFile(FileName(filename));
2881 else if (isDocBook()) {
2882 runparams.nice = !put_in_tempdir;
2883 makeDocBookFile(FileName(filename), runparams);
2886 else if (backend_format == format) {
2887 runparams.nice = true;
2888 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2890 } else if (!lyxrc.tex_allows_spaces
2891 && contains(filePath(), ' ')) {
2892 Alert::error(_("File name error"),
2893 _("The directory path to the document cannot contain spaces."));
2896 runparams.nice = false;
2897 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2901 string const error_type = (format == "program")
2902 ? "Build" : bufferFormat();
2903 ErrorList & error_list = d->errorLists[error_type];
2904 string const ext = formats.extension(format);
2905 FileName const tmp_result_file(changeExtension(filename, ext));
2906 bool const success = theConverters().convert(this, FileName(filename),
2907 tmp_result_file, FileName(absFileName()), backend_format, format,
2909 // Emit the signal to show the error list.
2910 if (format != backend_format) {
2912 // also to the children, in case of master-buffer-view
2913 std::vector<Buffer *> clist = getChildren();
2914 for (vector<Buffer *>::const_iterator cit = clist.begin();
2915 cit != clist.end(); ++cit)
2916 (*cit)->errors(error_type, true);
2921 if (put_in_tempdir) {
2922 result_file = tmp_result_file.absFilename();
2926 result_file = changeExtension(exportFileName().absFilename(), ext);
2927 // We need to copy referenced files (e. g. included graphics
2928 // if format == "dvi") to the result dir.
2929 vector<ExportedFile> const files =
2930 runparams.exportdata->externalFiles(format);
2931 string const dest = onlyPath(result_file);
2932 CopyStatus status = SUCCESS;
2933 for (vector<ExportedFile>::const_iterator it = files.begin();
2934 it != files.end() && status != CANCEL; ++it) {
2935 string const fmt = formats.getFormatFromFile(it->sourceName);
2936 status = copyFile(fmt, it->sourceName,
2937 makeAbsPath(it->exportName, dest),
2938 it->exportName, status == FORCE);
2940 if (status == CANCEL) {
2941 message(_("Document export cancelled."));
2942 } else if (tmp_result_file.exists()) {
2943 // Finally copy the main file
2944 status = copyFile(format, tmp_result_file,
2945 FileName(result_file), result_file,
2947 message(bformat(_("Document exported as %1$s "
2949 formats.prettyName(format),
2950 makeDisplayPath(result_file)));
2952 // This must be a dummy converter like fax (bug 1888)
2953 message(bformat(_("Document exported as %1$s"),
2954 formats.prettyName(format)));
2961 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2964 return doExport(format, put_in_tempdir, result_file);
2968 bool Buffer::preview(string const & format) const
2971 if (!doExport(format, true, result_file))
2973 return formats.view(*this, FileName(result_file), format);
2977 bool Buffer::isExportable(string const & format) const
2979 vector<string> backs = backends();
2980 for (vector<string>::const_iterator it = backs.begin();
2981 it != backs.end(); ++it)
2982 if (theConverters().isReachable(*it, format))
2988 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2990 vector<string> backs = backends();
2991 vector<Format const *> result =
2992 theConverters().getReachable(backs[0], only_viewable, true);
2993 for (vector<string>::const_iterator it = backs.begin() + 1;
2994 it != backs.end(); ++it) {
2995 vector<Format const *> r =
2996 theConverters().getReachable(*it, only_viewable, false);
2997 result.insert(result.end(), r.begin(), r.end());
3003 vector<string> Buffer::backends() const
3006 if (params().baseClass()->isTeXClassAvailable()) {
3007 v.push_back(bufferFormat());
3008 // FIXME: Don't hardcode format names here, but use a flag
3009 if (v.back() == "latex")
3010 v.push_back("pdflatex");
3012 v.push_back("text");
3013 v.push_back("xhtml");
3019 bool Buffer::readFileHelper(FileName const & s)
3021 // File information about normal file
3023 docstring const file = makeDisplayPath(s.absFilename(), 50);
3024 docstring text = bformat(_("The specified document\n%1$s"
3025 "\ncould not be read."), file);
3026 Alert::error(_("Could not read document"), text);
3030 // Check if emergency save file exists and is newer.
3031 FileName const e(s.absFilename() + ".emergency");
3033 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3034 docstring const file = makeDisplayPath(s.absFilename(), 20);
3035 docstring const text =
3036 bformat(_("An emergency save of the document "
3038 "Recover emergency save?"), file);
3039 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3040 _("&Recover"), _("&Load Original"),
3044 // the file is not saved if we load the emergency file.
3049 if ((res = readFile(e)) == success)
3050 str = _("Document was successfully recovered.");
3052 str = _("Document was NOT successfully recovered.");
3053 str += "\n\n" + _("Remove emergency file now?");
3055 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3056 _("&Remove"), _("&Keep it"))) {
3059 Alert::warning(_("Emergency file deleted"),
3060 _("Do not forget to save your file now!"), true);
3065 if (!Alert::prompt(_("Delete emergency file?"),
3066 _("Remove emergency file now?"), 1, 1,
3067 _("&Remove"), _("&Keep it")))
3075 // Now check if autosave file is newer.
3076 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3078 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3079 docstring const file = makeDisplayPath(s.absFilename(), 20);
3080 docstring const text =
3081 bformat(_("The backup of the document "
3082 "%1$s is newer.\n\nLoad the "
3083 "backup instead?"), file);
3084 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3085 _("&Load backup"), _("Load &original"),
3089 // the file is not saved if we load the autosave file.
3093 // Here we delete the autosave
3104 bool Buffer::loadLyXFile(FileName const & s)
3106 if (s.isReadableFile()) {
3107 if (readFileHelper(s)) {
3108 lyxvc().file_found_hook(s);
3109 if (!s.isWritable())
3114 docstring const file = makeDisplayPath(s.absFilename(), 20);
3115 // Here we probably should run
3116 if (LyXVC::file_not_found_hook(s)) {
3117 docstring const text =
3118 bformat(_("Do you want to retrieve the document"
3119 " %1$s from version control?"), file);
3120 int const ret = Alert::prompt(_("Retrieve from version control?"),
3121 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3124 // How can we know _how_ to do the checkout?
3125 // With the current VC support it has to be,
3126 // a RCS file since CVS do not have special ,v files.
3128 return loadLyXFile(s);
3136 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3138 TeXErrors::Errors::const_iterator cit = terr.begin();
3139 TeXErrors::Errors::const_iterator end = terr.end();
3141 for (; cit != end; ++cit) {
3144 int errorRow = cit->error_in_line;
3145 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3151 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3152 } while (found && id_start == id_end && pos_start == pos_end);
3154 errorList.push_back(ErrorItem(cit->error_desc,
3155 cit->error_text, id_start, pos_start, pos_end));
3160 void Buffer::setBuffersForInsets() const
3162 inset().setBuffer(const_cast<Buffer &>(*this));
3166 void Buffer::updateLabels(UpdateScope scope) const
3168 // Use the master text class also for child documents
3169 Buffer const * const master = masterBuffer();
3170 DocumentClass const & textclass = master->params().documentClass();
3172 // keep the buffers to be children in this set. If the call from the
3173 // master comes back we can see which of them were actually seen (i.e.
3174 // via an InsetInclude). The remaining ones in the set need still be updated.
3175 static std::set<Buffer const *> bufToUpdate;
3176 if (scope == UpdateMaster) {
3177 // If this is a child document start with the master
3178 if (master != this) {
3179 bufToUpdate.insert(this);
3180 master->updateLabels();
3181 // Do this here in case the master has no gui associated with it. Then,
3182 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3186 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3187 if (bufToUpdate.find(this) == bufToUpdate.end())
3191 // start over the counters in the master
3192 textclass.counters().reset();
3195 // update will be done below for this buffer
3196 bufToUpdate.erase(this);
3198 // update all caches
3199 clearReferenceCache();
3202 Buffer & cbuf = const_cast<Buffer &>(*this);
3204 LASSERT(!text().paragraphs().empty(), /**/);
3207 ParIterator parit = cbuf.par_iterator_begin();
3208 updateLabels(parit);
3211 // TocBackend update will be done later.
3214 cbuf.tocBackend().update();
3215 if (scope == UpdateMaster)
3216 cbuf.structureChanged();
3220 static depth_type getDepth(DocIterator const & it)
3222 depth_type depth = 0;
3223 for (size_t i = 0 ; i < it.depth() ; ++i)
3224 if (!it[i].inset().inMathed())
3225 depth += it[i].paragraph().getDepth() + 1;
3226 // remove 1 since the outer inset does not count
3230 static depth_type getItemDepth(ParIterator const & it)
3232 Paragraph const & par = *it;
3233 LabelType const labeltype = par.layout().labeltype;
3235 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3238 // this will hold the lowest depth encountered up to now.
3239 depth_type min_depth = getDepth(it);
3240 ParIterator prev_it = it;
3243 --prev_it.top().pit();
3245 // start of nested inset: go to outer par
3247 if (prev_it.empty()) {
3248 // start of document: nothing to do
3253 // We search for the first paragraph with same label
3254 // that is not more deeply nested.
3255 Paragraph & prev_par = *prev_it;
3256 depth_type const prev_depth = getDepth(prev_it);
3257 if (labeltype == prev_par.layout().labeltype) {
3258 if (prev_depth < min_depth)
3259 return prev_par.itemdepth + 1;
3260 if (prev_depth == min_depth)
3261 return prev_par.itemdepth;
3263 min_depth = min(min_depth, prev_depth);
3264 // small optimization: if we are at depth 0, we won't
3265 // find anything else
3266 if (prev_depth == 0)
3272 static bool needEnumCounterReset(ParIterator const & it)
3274 Paragraph const & par = *it;
3275 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3276 depth_type const cur_depth = par.getDepth();
3277 ParIterator prev_it = it;
3278 while (prev_it.pit()) {
3279 --prev_it.top().pit();
3280 Paragraph const & prev_par = *prev_it;
3281 if (prev_par.getDepth() <= cur_depth)
3282 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3284 // start of nested inset: reset
3289 // set the label of a paragraph. This includes the counters.
3290 static void setLabel(Buffer const & buf, ParIterator & it)
3292 BufferParams const & bp = buf.masterBuffer()->params();
3293 DocumentClass const & textclass = bp.documentClass();
3294 Paragraph & par = it.paragraph();
3295 Layout const & layout = par.layout();
3296 Counters & counters = textclass.counters();
3298 if (par.params().startOfAppendix()) {
3299 // FIXME: only the counter corresponding to toplevel
3300 // sectionning should be reset
3302 counters.appendix(true);
3304 par.params().appendix(counters.appendix());
3306 // Compute the item depth of the paragraph
3307 par.itemdepth = getItemDepth(it);
3309 if (layout.margintype == MARGIN_MANUAL
3310 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3311 if (par.params().labelWidthString().empty())
3312 par.params().labelWidthString(par.expandLabel(layout, bp));
3314 par.params().labelWidthString(docstring());
3317 switch(layout.labeltype) {
3319 if (layout.toclevel <= bp.secnumdepth
3320 && (layout.latextype != LATEX_ENVIRONMENT
3321 || it.text()->isFirstInSequence(it.pit()))) {
3322 counters.step(layout.counter);
3323 par.params().labelString(
3324 par.expandLabel(layout, bp));
3326 par.params().labelString(docstring());
3329 case LABEL_ITEMIZE: {
3330 // At some point of time we should do something more
3331 // clever here, like:
3332 // par.params().labelString(
3333 // bp.user_defined_bullet(par.itemdepth).getText());
3334 // for now, use a simple hardcoded label
3335 docstring itemlabel;
3336 switch (par.itemdepth) {
3338 itemlabel = char_type(0x2022);
3341 itemlabel = char_type(0x2013);
3344 itemlabel = char_type(0x2217);
3347 itemlabel = char_type(0x2219); // or 0x00b7
3350 par.params().labelString(itemlabel);
3354 case LABEL_ENUMERATE: {
3355 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3357 switch (par.itemdepth) {
3366 enumcounter += "iv";
3369 // not a valid enumdepth...
3373 // Maybe we have to reset the enumeration counter.
3374 if (needEnumCounterReset(it))
3375 counters.reset(enumcounter);
3376 counters.step(enumcounter);
3378 string const & lang = par.getParLanguage(bp)->code();
3379 par.params().labelString(counters.theCounter(enumcounter, lang));
3384 case LABEL_SENSITIVE: {
3385 string const & type = counters.current_float();
3386 docstring full_label;
3388 full_label = buf.B_("Senseless!!! ");
3390 docstring name = buf.B_(textclass.floats().getType(type).name());
3391 if (counters.hasCounter(from_utf8(type))) {
3392 string const & lang = par.getParLanguage(bp)->code();
3393 counters.step(from_utf8(type));
3394 full_label = bformat(from_ascii("%1$s %2$s:"),
3396 counters.theCounter(from_utf8(type), lang));
3398 full_label = bformat(from_ascii("%1$s #:"), name);
3400 par.params().labelString(full_label);
3404 case LABEL_NO_LABEL:
3405 par.params().labelString(docstring());
3409 case LABEL_TOP_ENVIRONMENT:
3410 case LABEL_CENTERED_TOP_ENVIRONMENT:
3413 par.params().labelString(par.expandLabel(layout, bp));
3419 void Buffer::updateLabels(ParIterator & parit) const
3421 LASSERT(parit.pit() == 0, /**/);
3423 // set the position of the text in the buffer to be able
3424 // to resolve macros in it. This has nothing to do with
3425 // labels, but by putting it here we avoid implementing
3426 // a whole bunch of traversal routines just for this call.
3427 parit.text()->setMacrocontextPosition(parit);
3429 depth_type maxdepth = 0;
3430 pit_type const lastpit = parit.lastpit();
3431 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3432 // reduce depth if necessary
3433 parit->params().depth(min(parit->params().depth(), maxdepth));
3434 maxdepth = parit->getMaxDepthAfter();
3436 // set the counter for this paragraph
3437 setLabel(*this, parit);
3440 InsetList::const_iterator iit = parit->insetList().begin();
3441 InsetList::const_iterator end = parit->insetList().end();
3442 for (; iit != end; ++iit) {
3443 parit.pos() = iit->pos;
3444 iit->inset->updateLabels(parit);
3450 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3451 WordLangTuple & word_lang, docstring_list & suggestions) const
3455 suggestions.clear();
3456 word_lang = WordLangTuple();
3457 // OK, we start from here.
3458 DocIterator const end = doc_iterator_end(this);
3459 for (; from != end; from.forwardPos()) {
3460 // We are only interested in text so remove the math CursorSlice.
3461 while (from.inMathed())
3462 from.forwardInset();
3464 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {