]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
* do not lookup the same macro all the time
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Buffer.h"
14
15 #include "Author.h"
16 #include "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "Counters.h"
21 #include "Bullet.h"
22 #include "Chktex.h"
23 #include "debug.h"
24 #include "Encoding.h"
25 #include "ErrorList.h"
26 #include "Exporter.h"
27 #include "Format.h"
28 #include "FuncRequest.h"
29 #include "gettext.h"
30 #include "InsetIterator.h"
31 #include "Language.h"
32 #include "LaTeX.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
35 #include "Lexer.h"
36 #include "Text.h"
37 #include "LyX.h"
38 #include "LyXRC.h"
39 #include "LyXVC.h"
40 #include "Messages.h"
41 #include "output.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "sgml.h"
49 #include "TexRow.h"
50 #include "TocBackend.h"
51 #include "Undo.h"
52 #include "version.h"
53
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetInclude.h"
57 #include "insets/InsetText.h"
58
59 #include "mathed/MathMacroTemplate.h"
60 #include "mathed/MacroTable.h"
61 #include "mathed/MathSupport.h"
62
63 #include "frontends/alert.h"
64
65 #include "graphics/Previews.h"
66
67 #include "support/types.h"
68 #include "support/lyxalgo.h"
69 #include "support/filetools.h"
70 #include "support/fs_extras.h"
71 #include "support/lyxlib.h"
72 #include "support/os.h"
73 #include "support/Path.h"
74 #include "support/textutils.h"
75 #include "support/convert.h"
76
77 #include <boost/iostreams/filtering_stream.hpp>
78 #include <boost/iostreams/filter/gzip.hpp>
79 #include <boost/iostreams/device/file.hpp>
80 #include <boost/bind.hpp>
81 #include <boost/filesystem/exception.hpp>
82 #include <boost/filesystem/operations.hpp>
83
84 #if defined (HAVE_UTIME_H)
85 #include <utime.h>
86 #elif defined (HAVE_SYS_UTIME_H)
87 #include <sys/utime.h>
88 #endif
89
90 #include <iomanip>
91 #include <stack>
92 #include <sstream>
93 #include <fstream>
94
95
96 namespace lyx {
97
98 using support::addName;
99 using support::bformat;
100 using support::changeExtension;
101 using support::cmd_ret;
102 using support::createBufferTmpDir;
103 using support::destroyDir;
104 using support::FileName;
105 using support::getFormatFromContents;
106 using support::libFileSearch;
107 using support::latex_path;
108 using support::ltrim;
109 using support::makeAbsPath;
110 using support::makeDisplayPath;
111 using support::makeLatexName;
112 using support::onlyFilename;
113 using support::onlyPath;
114 using support::quoteName;
115 using support::removeAutosaveFile;
116 using support::rename;
117 using support::runCommand;
118 using support::split;
119 using support::subst;
120 using support::tempName;
121 using support::trim;
122
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
125 namespace fs = boost::filesystem;
126 namespace io = boost::iostreams;
127
128 using std::endl;
129 using std::for_each;
130 using std::make_pair;
131
132 using std::ios;
133 using std::map;
134 using std::ostream;
135 using std::ostringstream;
136 using std::ofstream;
137 using std::pair;
138 using std::stack;
139 using std::vector;
140 using std::string;
141
142
143 namespace {
144
145 int const LYX_FORMAT = 271;
146
147 } // namespace anon
148
149
150 typedef std::map<string, bool> DepClean;
151
152 class Buffer::Impl
153 {
154 public:
155         Impl(Buffer & parent, FileName const & file, bool readonly);
156
157         limited_stack<Undo> undostack;
158         limited_stack<Undo> redostack;
159         BufferParams params;
160         LyXVC lyxvc;
161         string temppath;
162         TexRow texrow;
163
164         /// need to regenerate .tex?
165         DepClean dep_clean;
166
167         /// is save needed?
168         mutable bool lyx_clean;
169
170         /// is autosave needed?
171         mutable bool bak_clean;
172
173         /// is this a unnamed file (New...)?
174         bool unnamed;
175
176         /// buffer is r/o
177         bool read_only;
178
179         /// name of the file the buffer is associated with.
180         FileName filename;
181
182         /** Set to true only when the file is fully loaded.
183          *  Used to prevent the premature generation of previews
184          *  and by the citation inset.
185          */
186         bool file_fully_loaded;
187
188         /// our Text that should be wrapped in an InsetText
189         InsetText inset;
190
191         ///
192         MacroTable macros;
193
194         ///
195         TocBackend toc_backend;
196 };
197
198
199 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
200         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
201           filename(file), file_fully_loaded(false), inset(params),
202           toc_backend(&parent)
203 {
204         inset.setAutoBreakRows(true);
205         lyxvc.buffer(&parent);
206         temppath = createBufferTmpDir();
207         params.filepath = onlyPath(file.absFilename());
208         // FIXME: And now do something if temppath == string(), because we
209         // assume from now on that temppath points to a valid temp dir.
210         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
211 }
212
213
214 Buffer::Buffer(string const & file, bool readonly)
215         : pimpl_(new Impl(*this, FileName(file), readonly))
216 {
217         LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
218 }
219
220
221 Buffer::~Buffer()
222 {
223         LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
224         // here the buffer should take care that it is
225         // saved properly, before it goes into the void.
226
227         closing();
228
229         if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
230                 Alert::warning(_("Could not remove temporary directory"),
231                         bformat(_("Could not remove the temporary directory %1$s"),
232                         from_utf8(temppath())));
233         }
234
235         // Remove any previewed LaTeX snippets associated with this buffer.
236         graphics::Previews::get().removeLoader(*this);
237 }
238
239
240 Text & Buffer::text() const
241 {
242         return const_cast<Text &>(pimpl_->inset.text_);
243 }
244
245
246 Inset & Buffer::inset() const
247 {
248         return const_cast<InsetText &>(pimpl_->inset);
249 }
250
251
252 limited_stack<Undo> & Buffer::undostack()
253 {
254         return pimpl_->undostack;
255 }
256
257
258 limited_stack<Undo> const & Buffer::undostack() const
259 {
260         return pimpl_->undostack;
261 }
262
263
264 limited_stack<Undo> & Buffer::redostack()
265 {
266         return pimpl_->redostack;
267 }
268
269
270 limited_stack<Undo> const & Buffer::redostack() const
271 {
272         return pimpl_->redostack;
273 }
274
275
276 BufferParams & Buffer::params()
277 {
278         return pimpl_->params;
279 }
280
281
282 BufferParams const & Buffer::params() const
283 {
284         return pimpl_->params;
285 }
286
287
288 ParagraphList & Buffer::paragraphs()
289 {
290         return text().paragraphs();
291 }
292
293
294 ParagraphList const & Buffer::paragraphs() const
295 {
296         return text().paragraphs();
297 }
298
299
300 LyXVC & Buffer::lyxvc()
301 {
302         return pimpl_->lyxvc;
303 }
304
305
306 LyXVC const & Buffer::lyxvc() const
307 {
308         return pimpl_->lyxvc;
309 }
310
311
312 string const & Buffer::temppath() const
313 {
314         return pimpl_->temppath;
315 }
316
317
318 TexRow & Buffer::texrow()
319 {
320         return pimpl_->texrow;
321 }
322
323
324 TexRow const & Buffer::texrow() const
325 {
326         return pimpl_->texrow;
327 }
328
329
330 TocBackend & Buffer::tocBackend()
331 {
332         return pimpl_->toc_backend;
333 }
334
335
336 TocBackend const & Buffer::tocBackend() const
337 {
338         return pimpl_->toc_backend;
339 }
340
341
342 string const Buffer::getLatexName(bool const no_path) const
343 {
344         string const name = changeExtension(makeLatexName(fileName()), ".tex");
345         return no_path ? onlyFilename(name) : name;
346 }
347
348
349 pair<Buffer::LogType, string> const Buffer::getLogName() const
350 {
351         string const filename = getLatexName(false);
352
353         if (filename.empty())
354                 return make_pair(Buffer::latexlog, string());
355
356         string const path = temppath();
357
358         FileName const fname(addName(temppath(),
359                                      onlyFilename(changeExtension(filename,
360                                                                   ".log"))));
361         FileName const bname(
362                 addName(path, onlyFilename(
363                         changeExtension(filename,
364                                         formats.extension("literate") + ".out"))));
365
366         // If no Latex log or Build log is newer, show Build log
367
368         if (fs::exists(bname.toFilesystemEncoding()) &&
369             (!fs::exists(fname.toFilesystemEncoding()) ||
370              fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
371                 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
372                 return make_pair(Buffer::buildlog, bname.absFilename());
373         }
374         LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
375         return make_pair(Buffer::latexlog, fname.absFilename());
376 }
377
378
379 void Buffer::setReadonly(bool const flag)
380 {
381         if (pimpl_->read_only != flag) {
382                 pimpl_->read_only = flag;
383                 readonly(flag);
384         }
385 }
386
387
388 void Buffer::setFileName(string const & newfile)
389 {
390         pimpl_->filename = makeAbsPath(newfile);
391         params().filepath = onlyPath(pimpl_->filename.absFilename());
392         setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
393         updateTitles();
394 }
395
396
397 // We'll remove this later. (Lgb)
398 namespace {
399
400 void unknownClass(string const & unknown)
401 {
402         Alert::warning(_("Unknown document class"),
403                        bformat(_("Using the default document class, because the "
404                                               "class %1$s is unknown."), from_utf8(unknown)));
405 }
406
407 } // anon
408
409
410 int Buffer::readHeader(Lexer & lex)
411 {
412         int unknown_tokens = 0;
413         int line = -1;
414         int begin_header_line = -1;
415
416         // Initialize parameters that may be/go lacking in header:
417         params().branchlist().clear();
418         params().preamble.erase();
419         params().options.erase();
420         params().float_placement.erase();
421         params().paperwidth.erase();
422         params().paperheight.erase();
423         params().leftmargin.erase();
424         params().rightmargin.erase();
425         params().topmargin.erase();
426         params().bottommargin.erase();
427         params().headheight.erase();
428         params().headsep.erase();
429         params().footskip.erase();
430         for (int i = 0; i < 4; ++i) {
431                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
432                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
433         }
434
435         ErrorList & errorList = errorLists_["Parse"];
436
437         while (lex.isOK()) {
438                 lex.next();
439                 string const token = lex.getString();
440
441                 if (token.empty())
442                         continue;
443
444                 if (token == "\\end_header")
445                         break;
446
447                 ++line;
448                 if (token == "\\begin_header") {
449                         begin_header_line = line;
450                         continue;
451                 }
452
453                 LYXERR(Debug::PARSER) << "Handling document header token: `"
454                                       << token << '\'' << endl;
455
456                 string unknown = params().readToken(lex, token);
457                 if (!unknown.empty()) {
458                         if (unknown[0] != '\\' && token == "\\textclass") {
459                                 unknownClass(unknown);
460                         } else {
461                                 ++unknown_tokens;
462                                 docstring const s = bformat(_("Unknown token: "
463                                                                         "%1$s %2$s\n"),
464                                                          from_utf8(token),
465                                                          lex.getDocString());
466                                 errorList.push_back(ErrorItem(_("Document header error"),
467                                         s, -1, 0, 0));
468                         }
469                 }
470         }
471         if (begin_header_line) {
472                 docstring const s = _("\\begin_header is missing");
473                 errorList.push_back(ErrorItem(_("Document header error"),
474                         s, -1, 0, 0));
475         }
476
477         return unknown_tokens;
478 }
479
480
481 // Uwe C. Schroeder
482 // changed to be public and have one parameter
483 // Returns false if "\end_document" is not read (Asger)
484 bool Buffer::readDocument(Lexer & lex)
485 {
486         ErrorList & errorList = errorLists_["Parse"];
487         errorList.clear();
488
489         lex.next();
490         string const token = lex.getString();
491         if (token != "\\begin_document") {
492                 docstring const s = _("\\begin_document is missing");
493                 errorList.push_back(ErrorItem(_("Document header error"),
494                         s, -1, 0, 0));
495         }
496
497         // we are reading in a brand new document
498         BOOST_ASSERT(paragraphs().empty());
499
500         readHeader(lex);
501         if (!params().getTextClass().load(filePath())) {
502                 string theclass = params().getTextClass().name();
503                 Alert::error(_("Can't load document class"), bformat(
504                         _("Using the default document class, because the "
505                                      "class %1$s could not be loaded."), from_utf8(theclass)));
506                 params().textclass = 0;
507         }
508
509         if (params().outputChanges) {
510                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
511                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
512                                   LaTeXFeatures::isAvailable("xcolor");
513                 
514                 if (!dvipost && !xcolorsoul) {
515                         Alert::warning(_("Changes not shown in LaTeX output"),
516                                        _("Changes will not be highlighted in LaTeX output, "
517                                          "because neither dvipost nor xcolor/soul are installed.\n"
518                                          "Please install these packages or redefine "
519                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
520                 } else if (!xcolorsoul) {
521                         Alert::warning(_("Changes not shown in LaTeX output"),
522                                        _("Changes will not be highlighted in LaTeX output "
523                                          "when using pdflatex, because xcolor and soul are not installed.\n"
524                                          "Please install both packages or redefine "
525                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
526                 }
527         }
528
529         bool const res = text().read(*this, lex, errorList);
530         for_each(text().paragraphs().begin(),
531                  text().paragraphs().end(),
532                  bind(&Paragraph::setInsetOwner, _1, &inset()));
533
534         return res;
535 }
536
537
538 // needed to insert the selection
539 void Buffer::insertStringAsLines(ParagraphList & pars,
540         pit_type & pit, pos_type & pos,
541         Font const & fn, docstring const & str, bool autobreakrows)
542 {
543         Font font = fn;
544
545         // insert the string, don't insert doublespace
546         bool space_inserted = true;
547         for (docstring::const_iterator cit = str.begin();
548             cit != str.end(); ++cit) {
549                 Paragraph & par = pars[pit];
550                 if (*cit == '\n') {
551                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
552                                 breakParagraph(params(), pars, pit, pos,
553                                                par.layout()->isEnvironment());
554                                 ++pit;
555                                 pos = 0;
556                                 space_inserted = true;
557                         } else {
558                                 continue;
559                         }
560                         // do not insert consecutive spaces if !free_spacing
561                 } else if ((*cit == ' ' || *cit == '\t') &&
562                            space_inserted && !par.isFreeSpacing()) {
563                         continue;
564                 } else if (*cit == '\t') {
565                         if (!par.isFreeSpacing()) {
566                                 // tabs are like spaces here
567                                 par.insertChar(pos, ' ', font, params().trackChanges);
568                                 ++pos;
569                                 space_inserted = true;
570                         } else {
571                                 const pos_type n = 8 - pos % 8;
572                                 for (pos_type i = 0; i < n; ++i) {
573                                         par.insertChar(pos, ' ', font, params().trackChanges);
574                                         ++pos;
575                                 }
576                                 space_inserted = true;
577                         }
578                 } else if (!isPrintable(*cit)) {
579                         // Ignore unprintables
580                         continue;
581                 } else {
582                         // just insert the character
583                         par.insertChar(pos, *cit, font, params().trackChanges);
584                         ++pos;
585                         space_inserted = (*cit == ' ');
586                 }
587
588         }
589 }
590
591
592 bool Buffer::readString(std::string const & s)
593 {
594         params().compressed = false;
595
596         // remove dummy empty par
597         paragraphs().clear();
598         Lexer lex(0, 0);
599         std::istringstream is(s);
600         lex.setStream(is);
601         FileName const name(tempName());
602         switch (readFile(lex, name, true)) {
603         case failure:
604                 return false;
605         case wrongversion: {
606                 // We need to call lyx2lyx, so write the input to a file
607                 std::ofstream os(name.toFilesystemEncoding().c_str());
608                 os << s;
609                 os.close();
610                 return readFile(name);
611         }
612         case success:
613                 break;
614         }
615
616         return true;
617 }
618
619
620 bool Buffer::readFile(FileName const & filename)
621 {
622         // Check if the file is compressed.
623         string const format = getFormatFromContents(filename);
624         if (format == "gzip" || format == "zip" || format == "compress") {
625                 params().compressed = true;
626         }
627
628         // remove dummy empty par
629         paragraphs().clear();
630         Lexer lex(0, 0);
631         lex.setFile(filename);
632         if (readFile(lex, filename) != success)
633                 return false;
634
635         return true;
636 }
637
638
639 bool Buffer::fully_loaded() const
640 {
641         return pimpl_->file_fully_loaded;
642 }
643
644
645 void Buffer::fully_loaded(bool const value)
646 {
647         pimpl_->file_fully_loaded = value;
648 }
649
650
651 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
652                 bool fromstring)
653 {
654         BOOST_ASSERT(!filename.empty());
655
656         if (!lex.isOK()) {
657                 Alert::error(_("Document could not be read"),
658                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
659                 return failure;
660         }
661
662         lex.next();
663         string const token(lex.getString());
664
665         if (!lex) {
666                 Alert::error(_("Document could not be read"),
667                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
668                 return failure;
669         }
670
671         // the first token _must_ be...
672         if (token != "\\lyxformat") {
673                 lyxerr << "Token: " << token << endl;
674
675                 Alert::error(_("Document format failure"),
676                              bformat(_("%1$s is not a LyX document."),
677                                        from_utf8(filename.absFilename())));
678                 return failure;
679         }
680
681         lex.next();
682         string tmp_format = lex.getString();
683         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
684         // if present remove ".," from string.
685         string::size_type dot = tmp_format.find_first_of(".,");
686         //lyxerr << "           dot found at " << dot << endl;
687         if (dot != string::npos)
688                         tmp_format.erase(dot, 1);
689         int const file_format = convert<int>(tmp_format);
690         //lyxerr << "format: " << file_format << endl;
691
692         if (file_format != LYX_FORMAT) {
693
694                 if (fromstring)
695                         // lyx2lyx would fail
696                         return wrongversion;
697
698                 FileName const tmpfile(tempName());
699                 if (tmpfile.empty()) {
700                         Alert::error(_("Conversion failed"),
701                                      bformat(_("%1$s is from a different"
702                                               " version of LyX, but a temporary"
703                                               " file for converting it could"
704                                                             " not be created."),
705                                               from_utf8(filename.absFilename())));
706                         return failure;
707                 }
708                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
709                 if (lyx2lyx.empty()) {
710                         Alert::error(_("Conversion script not found"),
711                                      bformat(_("%1$s is from a different"
712                                                " version of LyX, but the"
713                                                " conversion script lyx2lyx"
714                                                             " could not be found."),
715                                                from_utf8(filename.absFilename())));
716                         return failure;
717                 }
718                 ostringstream command;
719                 command << os::python()
720                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
721                         << " -t " << convert<string>(LYX_FORMAT)
722                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
723                         << ' ' << quoteName(filename.toFilesystemEncoding());
724                 string const command_str = command.str();
725
726                 LYXERR(Debug::INFO) << "Running '"
727                                     << command_str << '\''
728                                     << endl;
729
730                 cmd_ret const ret = runCommand(command_str);
731                 if (ret.first != 0) {
732                         Alert::error(_("Conversion script failed"),
733                                      bformat(_("%1$s is from a different version"
734                                               " of LyX, but the lyx2lyx script"
735                                                             " failed to convert it."),
736                                               from_utf8(filename.absFilename())));
737                         return failure;
738                 } else {
739                         bool const ret = readFile(tmpfile);
740                         // Do stuff with tmpfile name and buffer name here.
741                         return ret ? success : failure;
742                 }
743
744         }
745
746         if (readDocument(lex)) {
747                 Alert::error(_("Document format failure"),
748                              bformat(_("%1$s ended unexpectedly, which means"
749                                                     " that it is probably corrupted."),
750                                        from_utf8(filename.absFilename())));
751         }
752
753         //lyxerr << "removing " << MacroTable::localMacros().size()
754         //      << " temporary macro entries" << endl;
755         //MacroTable::localMacros().clear();
756
757         pimpl_->file_fully_loaded = true;
758         return success;
759 }
760
761
762 // Should probably be moved to somewhere else: BufferView? LyXView?
763 bool Buffer::save() const
764 {
765         // We don't need autosaves in the immediate future. (Asger)
766         resetAutosaveTimers();
767
768         string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
769
770         FileName backupName;
771         bool madeBackup = false;
772
773         // make a backup if the file already exists
774         if (lyxrc.make_backup && fs::exists(encodedFilename)) {
775                 backupName = FileName(fileName() + '~');
776                 if (!lyxrc.backupdir_path.empty())
777                         backupName = FileName(addName(lyxrc.backupdir_path,
778                                               subst(os::internal_path(backupName.absFilename()), '/', '!')));
779
780                 try {
781                         fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
782                         madeBackup = true;
783                 } catch (fs::filesystem_error const & fe) {
784                         Alert::error(_("Backup failure"),
785                                      bformat(_("Cannot create backup file %1$s.\n"
786                                                "Please check whether the directory exists and is writeable."),
787                                              from_utf8(backupName.absFilename())));
788                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
789                 }
790         }
791
792         if (writeFile(pimpl_->filename)) {
793                 markClean();
794                 removeAutosaveFile(fileName());
795                 return true;
796         } else {
797                 // Saving failed, so backup is not backup
798                 if (madeBackup)
799                         rename(backupName, pimpl_->filename);
800                 return false;
801         }
802 }
803
804
805 bool Buffer::writeFile(FileName const & fname) const
806 {
807         if (pimpl_->read_only && fname == pimpl_->filename)
808                 return false;
809
810         bool retval = false;
811
812         if (params().compressed) {
813                 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
814                 if (!ofs)
815                         return false;
816
817                 retval = write(ofs);
818         } else {
819                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
820                 if (!ofs)
821                         return false;
822
823                 retval = write(ofs);
824         }
825
826         return retval;
827 }
828
829
830 bool Buffer::write(ostream & ofs) const
831 {
832 #ifdef HAVE_LOCALE
833         // Use the standard "C" locale for file output.
834         ofs.imbue(std::locale::classic());
835 #endif
836
837         // The top of the file should not be written by params().
838
839         // write out a comment in the top of the file
840         ofs << "#LyX " << lyx_version
841             << " created this file. For more info see http://www.lyx.org/\n"
842             << "\\lyxformat " << LYX_FORMAT << "\n"
843             << "\\begin_document\n";
844
845         // now write out the buffer parameters.
846         ofs << "\\begin_header\n";
847         params().writeFile(ofs);
848         ofs << "\\end_header\n";
849
850         // write the text
851         ofs << "\n\\begin_body\n";
852         text().write(*this, ofs);
853         ofs << "\n\\end_body\n";
854
855         // Write marker that shows file is complete
856         ofs << "\\end_document" << endl;
857
858         // Shouldn't really be needed....
859         //ofs.close();
860
861         // how to check if close went ok?
862         // Following is an attempt... (BE 20001011)
863
864         // good() returns false if any error occured, including some
865         //        formatting error.
866         // bad()  returns true if something bad happened in the buffer,
867         //        which should include file system full errors.
868
869         bool status = true;
870         if (!ofs) {
871                 status = false;
872                 lyxerr << "File was not closed properly." << endl;
873         }
874
875         return status;
876 }
877
878
879 bool Buffer::makeLaTeXFile(FileName const & fname,
880                            string const & original_path,
881                            OutputParams const & runparams,
882                            bool output_preamble, bool output_body)
883 {
884         string const encoding = runparams.encoding->iconvName();
885         LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
886                 << encoding << "..." << endl;
887
888         odocfstream ofs(encoding);
889         if (!openFileWrite(ofs, fname))
890                 return false;
891
892         bool failed_export = false;
893         try {
894                 writeLaTeXSource(ofs, original_path,
895                       runparams, output_preamble, output_body);
896         }
897         catch (iconv_codecvt_facet_exception & e) {
898                 lyxerr << "Caught iconv exception: " << e.what() << endl;
899                 failed_export = true;
900         }
901         catch (std::exception  const & e) {
902                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
903                 failed_export = true;
904         }
905         catch (...) {
906                 lyxerr << "Caught some really weird exception..." << endl;
907                 LyX::cref().emergencyCleanup();
908                 abort();
909         }
910
911         ofs.close();
912         if (ofs.fail()) {
913                 failed_export = true;
914                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
915         }
916
917         if (failed_export) {
918                 Alert::error(_("Encoding error"),
919                         _("Some characters of your document are probably not "
920                         "representable in the chosen encoding.\n"
921                         "Changing the document encoding to utf8 could help."));
922                 return false;
923         }
924         return true;
925 }
926
927
928 void Buffer::writeLaTeXSource(odocstream & os,
929                            string const & original_path,
930                            OutputParams const & runparams_in,
931                            bool const output_preamble, bool const output_body)
932 {
933         OutputParams runparams = runparams_in;
934
935         // validate the buffer.
936         LYXERR(Debug::LATEX) << "  Validating buffer..." << endl;
937         LaTeXFeatures features(*this, params(), runparams);
938         validate(features);
939         LYXERR(Debug::LATEX) << "  Buffer validation done." << endl;
940
941         texrow().reset();
942
943         // The starting paragraph of the coming rows is the
944         // first paragraph of the document. (Asger)
945         texrow().start(paragraphs().begin()->id(), 0);
946
947         if (output_preamble && runparams.nice) {
948                 os << "%% LyX " << lyx_version << " created this file.  "
949                         "For more info, see http://www.lyx.org/.\n"
950                         "%% Do not edit unless you really know what "
951                         "you are doing.\n";
952                 texrow().newline();
953                 texrow().newline();
954         }
955         LYXERR(Debug::INFO) << "lyx document header finished" << endl;
956         // There are a few differences between nice LaTeX and usual files:
957         // usual is \batchmode and has a
958         // special input@path to allow the including of figures
959         // with either \input or \includegraphics (what figinsets do).
960         // input@path is set when the actual parameter
961         // original_path is set. This is done for usual tex-file, but not
962         // for nice-latex-file. (Matthias 250696)
963         // Note that input@path is only needed for something the user does
964         // in the preamble, included .tex files or ERT, files included by
965         // LyX work without it.
966         if (output_preamble) {
967                 if (!runparams.nice) {
968                         // code for usual, NOT nice-latex-file
969                         os << "\\batchmode\n"; // changed
970                         // from \nonstopmode
971                         texrow().newline();
972                 }
973                 if (!original_path.empty()) {
974                         // FIXME UNICODE
975                         // We don't know the encoding of inputpath
976                         docstring const inputpath = from_utf8(latex_path(original_path));
977                         os << "\\makeatletter\n"
978                            << "\\def\\input@path{{"
979                            << inputpath << "/}}\n"
980                            << "\\makeatother\n";
981                         texrow().newline();
982                         texrow().newline();
983                         texrow().newline();
984                 }
985
986                 // Write the preamble
987                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
988
989                 if (!output_body)
990                         return;
991
992                 // make the body.
993                 os << "\\begin{document}\n";
994                 texrow().newline();
995         } // output_preamble
996         LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
997
998         if (!lyxrc.language_auto_begin &&
999             !params().language->babel().empty()) {
1000                 // FIXME UNICODE
1001                 os << from_utf8(subst(lyxrc.language_command_begin,
1002                                            "$$lang",
1003                                            params().language->babel()))
1004                    << '\n';
1005                 texrow().newline();
1006         }
1007
1008         Encoding const & encoding = params().encoding();
1009         if (encoding.package() == Encoding::CJK) {
1010                 // Open a CJK environment, since in contrast to the encodings
1011                 // handled by inputenc the document encoding is not set in
1012                 // the preamble if it is handled by CJK.sty.
1013                 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1014                    << "}{}\n";
1015                 texrow().newline();
1016         }
1017
1018         // if we are doing a real file with body, even if this is the
1019         // child of some other buffer, let's cut the link here.
1020         // This happens for example if only a child document is printed.
1021         string save_parentname;
1022         if (output_preamble) {
1023                 save_parentname = params().parentname;
1024                 params().parentname.erase();
1025         }
1026
1027         // the real stuff
1028         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1029
1030         // Restore the parenthood if needed
1031         if (output_preamble)
1032                 params().parentname = save_parentname;
1033
1034         // add this just in case after all the paragraphs
1035         os << endl;
1036         texrow().newline();
1037
1038         if (encoding.package() == Encoding::CJK) {
1039                 // Close the open CJK environment.
1040                 // latexParagraphs will have opened one even if the last text
1041                 // was not CJK.
1042                 os << "\\end{CJK}\n";
1043                 texrow().newline();
1044         }
1045
1046         if (!lyxrc.language_auto_end &&
1047             !params().language->babel().empty()) {
1048                 os << from_utf8(subst(lyxrc.language_command_end,
1049                                            "$$lang",
1050                                            params().language->babel()))
1051                    << '\n';
1052                 texrow().newline();
1053         }
1054
1055         if (output_preamble) {
1056                 os << "\\end{document}\n";
1057                 texrow().newline();
1058
1059                 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1060         } else {
1061                 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1062                                      << endl;
1063         }
1064         runparams_in.encoding = runparams.encoding;
1065
1066         // Just to be sure. (Asger)
1067         texrow().newline();
1068
1069         LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1070         LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1071                             << '.' << endl;
1072 }
1073
1074
1075 bool Buffer::isLatex() const
1076 {
1077         return params().getTextClass().outputType() == LATEX;
1078 }
1079
1080
1081 bool Buffer::isLiterate() const
1082 {
1083         return params().getTextClass().outputType() == LITERATE;
1084 }
1085
1086
1087 bool Buffer::isDocBook() const
1088 {
1089         return params().getTextClass().outputType() == DOCBOOK;
1090 }
1091
1092
1093 void Buffer::makeDocBookFile(FileName const & fname,
1094                               OutputParams const & runparams,
1095                               bool const body_only)
1096 {
1097         LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1098
1099         //ofstream ofs;
1100         odocfstream ofs;
1101         if (!openFileWrite(ofs, fname))
1102                 return;
1103
1104         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1105
1106         ofs.close();
1107         if (ofs.fail())
1108                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1109 }
1110
1111
1112 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1113                              OutputParams const & runparams,
1114                              bool const only_body)
1115 {
1116         LaTeXFeatures features(*this, params(), runparams);
1117         validate(features);
1118
1119         texrow().reset();
1120
1121         TextClass const & tclass = params().getTextClass();
1122         string const top_element = tclass.latexname();
1123
1124         if (!only_body) {
1125                 if (runparams.flavor == OutputParams::XML)
1126                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1127
1128                 // FIXME UNICODE
1129                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1130
1131                 // FIXME UNICODE
1132                 if (! tclass.class_header().empty())
1133                         os << from_ascii(tclass.class_header());
1134                 else if (runparams.flavor == OutputParams::XML)
1135                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1136                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1137                 else
1138                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1139
1140                 docstring preamble = from_utf8(params().preamble);
1141                 if (runparams.flavor != OutputParams::XML ) {
1142                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1143                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1144                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1145                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1146                 }
1147
1148                 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1149                          : fname;
1150                 preamble += features.getIncludedFiles(name);
1151                 preamble += features.getLyXSGMLEntities();
1152
1153                 if (!preamble.empty()) {
1154                         os << "\n [ " << preamble << " ]";
1155                 }
1156                 os << ">\n\n";
1157         }
1158
1159         string top = top_element;
1160         top += " lang=\"";
1161         if (runparams.flavor == OutputParams::XML)
1162                 top += params().language->code();
1163         else
1164                 top += params().language->code().substr(0,2);
1165         top += '"';
1166
1167         if (!params().options.empty()) {
1168                 top += ' ';
1169                 top += params().options;
1170         }
1171
1172         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1173             << " file was created by LyX " << lyx_version
1174             << "\n  See http://www.lyx.org/ for more information -->\n";
1175
1176         params().getTextClass().counters().reset();
1177
1178         sgml::openTag(os, top);
1179         os << '\n';
1180         docbookParagraphs(paragraphs(), *this, os, runparams);
1181         sgml::closeTag(os, top_element);
1182 }
1183
1184
1185 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1186 // Other flags: -wall -v0 -x
1187 int Buffer::runChktex()
1188 {
1189         busy(true);
1190
1191         // get LaTeX-Filename
1192         FileName const path(temppath());
1193         string const name = addName(path.absFilename(), getLatexName());
1194         string const org_path = filePath();
1195
1196         support::Path p(path); // path to LaTeX file
1197         message(_("Running chktex..."));
1198
1199         // Generate the LaTeX file if neccessary
1200         OutputParams runparams(&params().encoding());
1201         runparams.flavor = OutputParams::LATEX;
1202         runparams.nice = false;
1203         makeLaTeXFile(FileName(name), org_path, runparams);
1204
1205         TeXErrors terr;
1206         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1207         int const res = chktex.run(terr); // run chktex
1208
1209         if (res == -1) {
1210                 Alert::error(_("chktex failure"),
1211                              _("Could not run chktex successfully."));
1212         } else if (res > 0) {
1213                 ErrorList & errorList = errorLists_["ChkTeX"];
1214                 // Clear out old errors
1215                 errorList.clear();
1216                 // Fill-in the error list with the TeX errors
1217                 bufferErrors(*this, terr, errorList);
1218         }
1219
1220         busy(false);
1221
1222         errors("ChkTeX");
1223
1224         return res;
1225 }
1226
1227
1228 void Buffer::validate(LaTeXFeatures & features) const
1229 {
1230         TextClass const & tclass = params().getTextClass();
1231
1232         if (params().outputChanges) {
1233                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1234                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1235                                   LaTeXFeatures::isAvailable("xcolor");
1236                 
1237                 if (features.runparams().flavor == OutputParams::LATEX) {
1238                         if (dvipost) {
1239                                 features.require("ct-dvipost");
1240                                 features.require("dvipost");
1241                         } else if (xcolorsoul) {
1242                                 features.require("ct-xcolor-soul");
1243                                 features.require("soul");
1244                                 features.require("xcolor");
1245                         } else {        
1246                                 features.require("ct-none");
1247                         }
1248                 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1249                         if (xcolorsoul) {
1250                                 features.require("ct-xcolor-soul");
1251                                 features.require("soul");
1252                                 features.require("xcolor");
1253                                 features.require("pdfcolmk"); // improves color handling in PDF output
1254                         } else {
1255                                 features.require("ct-none");
1256                         }
1257                 }
1258         }
1259
1260         // AMS Style is at document level
1261         if (params().use_amsmath == BufferParams::package_on
1262             || tclass.provides("amsmath"))
1263                 features.require("amsmath");
1264         if (params().use_esint == BufferParams::package_on)
1265                 features.require("esint");
1266
1267         for_each(paragraphs().begin(), paragraphs().end(),
1268                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1269
1270         // the bullet shapes are buffer level not paragraph level
1271         // so they are tested here
1272         for (int i = 0; i < 4; ++i) {
1273                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1274                         int const font = params().user_defined_bullet(i).getFont();
1275                         if (font == 0) {
1276                                 int const c = params()
1277                                         .user_defined_bullet(i)
1278                                         .getCharacter();
1279                                 if (c == 16
1280                                    || c == 17
1281                                    || c == 25
1282                                    || c == 26
1283                                    || c == 31) {
1284                                         features.require("latexsym");
1285                                 }
1286                         } else if (font == 1) {
1287                                 features.require("amssymb");
1288                         } else if ((font >= 2 && font <= 5)) {
1289                                 features.require("pifont");
1290                         }
1291                 }
1292         }
1293
1294         if (lyxerr.debugging(Debug::LATEX)) {
1295                 features.showStruct();
1296         }
1297 }
1298
1299
1300 void Buffer::getLabelList(vector<docstring> & list) const
1301 {
1302         /// if this is a child document and the parent is already loaded
1303         /// Use the parent's list instead  [ale990407]
1304         Buffer const * tmp = getMasterBuffer();
1305         if (!tmp) {
1306                 lyxerr << "getMasterBuffer() failed!" << endl;
1307                 BOOST_ASSERT(tmp);
1308         }
1309         if (tmp != this) {
1310                 tmp->getLabelList(list);
1311                 return;
1312         }
1313
1314         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1315                 it.nextInset()->getLabelList(*this, list);
1316 }
1317
1318
1319 // This is also a buffer property (ale)
1320 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1321         const
1322 {
1323         /// if this is a child document and the parent is already loaded
1324         /// use the parent's list instead  [ale990412]
1325         Buffer const * tmp = getMasterBuffer();
1326         BOOST_ASSERT(tmp);
1327         if (tmp != this) {
1328                 tmp->fillWithBibKeys(keys);
1329                 return;
1330         }
1331
1332         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1333                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1334                         InsetBibtex const & inset =
1335                                 static_cast<InsetBibtex const &>(*it);
1336                         inset.fillWithBibKeys(*this, keys);
1337                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1338                         InsetInclude const & inset =
1339                                 static_cast<InsetInclude const &>(*it);
1340                         inset.fillWithBibKeys(*this, keys);
1341                 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1342                         InsetBibitem const & inset =
1343                                 static_cast<InsetBibitem const &>(*it);
1344                         // FIXME UNICODE
1345                         string const key = to_utf8(inset.getParam("key"));
1346                         docstring const label = inset.getParam("label");
1347                         DocIterator doc_it(it); doc_it.forwardPos();
1348                         docstring const ref = doc_it.paragraph().asString(*this, false);
1349                         docstring const info = label + "TheBibliographyRef" + ref;
1350                         keys.push_back(pair<string, docstring>(key, info));
1351                 }
1352         }
1353 }
1354
1355
1356 void Buffer::updateBibfilesCache()
1357 {
1358         // if this is a child document and the parent is already loaded
1359         // update the parent's cache instead
1360         Buffer * tmp = getMasterBuffer();
1361         BOOST_ASSERT(tmp);
1362         if (tmp != this) {
1363                 tmp->updateBibfilesCache();
1364                 return;
1365         }
1366
1367         bibfilesCache_.clear();
1368         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1369                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1370                         InsetBibtex const & inset =
1371                                 static_cast<InsetBibtex const &>(*it);
1372                         vector<FileName> const bibfiles = inset.getFiles(*this);
1373                         bibfilesCache_.insert(bibfilesCache_.end(),
1374                                 bibfiles.begin(),
1375                                 bibfiles.end());
1376                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1377                         InsetInclude & inset =
1378                                 static_cast<InsetInclude &>(*it);
1379                         inset.updateBibfilesCache(*this);
1380                         vector<FileName> const & bibfiles =
1381                                         inset.getBibfilesCache(*this);
1382                         bibfilesCache_.insert(bibfilesCache_.end(),
1383                                 bibfiles.begin(),
1384                                 bibfiles.end());
1385                 }
1386         }
1387 }
1388
1389
1390 vector<FileName> const & Buffer::getBibfilesCache() const
1391 {
1392         // if this is a child document and the parent is already loaded
1393         // use the parent's cache instead
1394         Buffer const * tmp = getMasterBuffer();
1395         BOOST_ASSERT(tmp);
1396         if (tmp != this)
1397                 return tmp->getBibfilesCache();
1398
1399         // We update the cache when first used instead of at loading time.
1400         if (bibfilesCache_.empty())
1401                 const_cast<Buffer *>(this)->updateBibfilesCache();
1402
1403         return bibfilesCache_;
1404 }
1405
1406
1407 bool Buffer::isDepClean(string const & name) const
1408 {
1409         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1410         if (it == pimpl_->dep_clean.end())
1411                 return true;
1412         return it->second;
1413 }
1414
1415
1416 void Buffer::markDepClean(string const & name)
1417 {
1418         pimpl_->dep_clean[name] = true;
1419 }
1420
1421
1422 bool Buffer::dispatch(string const & command, bool * result)
1423 {
1424         return dispatch(lyxaction.lookupFunc(command), result);
1425 }
1426
1427
1428 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1429 {
1430         bool dispatched = true;
1431
1432         switch (func.action) {
1433                 case LFUN_BUFFER_EXPORT: {
1434                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1435                         if (result)
1436                                 *result = tmp;
1437                         break;
1438                 }
1439
1440                 default:
1441                         dispatched = false;
1442         }
1443         return dispatched;
1444 }
1445
1446
1447 void Buffer::changeLanguage(Language const * from, Language const * to)
1448 {
1449         BOOST_ASSERT(from);
1450         BOOST_ASSERT(to);
1451
1452         for_each(par_iterator_begin(),
1453                  par_iterator_end(),
1454                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1455
1456         text().current_font.setLanguage(to);
1457         text().real_current_font.setLanguage(to);
1458 }
1459
1460
1461 bool Buffer::isMultiLingual() const
1462 {
1463         ParConstIterator end = par_iterator_end();
1464         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1465                 if (it->isMultiLingual(params()))
1466                         return true;
1467
1468         return false;
1469 }
1470
1471
1472 ParIterator Buffer::getParFromID(int const id) const
1473 {
1474         ParConstIterator it = par_iterator_begin();
1475         ParConstIterator const end = par_iterator_end();
1476
1477         if (id < 0) {
1478                 // John says this is called with id == -1 from undo
1479                 lyxerr << "getParFromID(), id: " << id << endl;
1480                 return end;
1481         }
1482
1483         for (; it != end; ++it)
1484                 if (it->id() == id)
1485                         return it;
1486
1487         return end;
1488 }
1489
1490
1491 bool Buffer::hasParWithID(int const id) const
1492 {
1493         ParConstIterator const it = getParFromID(id);
1494         return it != par_iterator_end();
1495 }
1496
1497
1498 ParIterator Buffer::par_iterator_begin()
1499 {
1500         return lyx::par_iterator_begin(inset());
1501 }
1502
1503
1504 ParIterator Buffer::par_iterator_end()
1505 {
1506         return lyx::par_iterator_end(inset());
1507 }
1508
1509
1510 ParConstIterator Buffer::par_iterator_begin() const
1511 {
1512         return lyx::par_const_iterator_begin(inset());
1513 }
1514
1515
1516 ParConstIterator Buffer::par_iterator_end() const
1517 {
1518         return lyx::par_const_iterator_end(inset());
1519 }
1520
1521
1522 Language const * Buffer::getLanguage() const
1523 {
1524         return params().language;
1525 }
1526
1527
1528 docstring const Buffer::B_(string const & l10n) const
1529 {
1530         return params().B_(l10n);
1531 }
1532
1533
1534 bool Buffer::isClean() const
1535 {
1536         return pimpl_->lyx_clean;
1537 }
1538
1539
1540 bool Buffer::isBakClean() const
1541 {
1542         return pimpl_->bak_clean;
1543 }
1544
1545
1546 void Buffer::markClean() const
1547 {
1548         if (!pimpl_->lyx_clean) {
1549                 pimpl_->lyx_clean = true;
1550                 updateTitles();
1551         }
1552         // if the .lyx file has been saved, we don't need an
1553         // autosave
1554         pimpl_->bak_clean = true;
1555 }
1556
1557
1558 void Buffer::markBakClean()
1559 {
1560         pimpl_->bak_clean = true;
1561 }
1562
1563
1564 void Buffer::setUnnamed(bool flag)
1565 {
1566         pimpl_->unnamed = flag;
1567 }
1568
1569
1570 bool Buffer::isUnnamed() const
1571 {
1572         return pimpl_->unnamed;
1573 }
1574
1575
1576 #ifdef WITH_WARNINGS
1577 #warning this function should be moved to buffer_pimpl.C
1578 #endif
1579 void Buffer::markDirty()
1580 {
1581         if (pimpl_->lyx_clean) {
1582                 pimpl_->lyx_clean = false;
1583                 updateTitles();
1584         }
1585         pimpl_->bak_clean = false;
1586
1587         DepClean::iterator it = pimpl_->dep_clean.begin();
1588         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1589
1590         for (; it != end; ++it)
1591                 it->second = false;
1592 }
1593
1594
1595 string const Buffer::fileName() const
1596 {
1597         return pimpl_->filename.absFilename();
1598 }
1599
1600
1601 string const & Buffer::filePath() const
1602 {
1603         return params().filepath;
1604 }
1605
1606
1607 bool Buffer::isReadonly() const
1608 {
1609         return pimpl_->read_only;
1610 }
1611
1612
1613 void Buffer::setParentName(string const & name)
1614 {
1615         params().parentname = name;
1616 }
1617
1618
1619 Buffer const * Buffer::getMasterBuffer() const
1620 {
1621         if (!params().parentname.empty()
1622             && theBufferList().exists(params().parentname)) {
1623                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1624                 //We need to check if the parent is us...
1625                 //FIXME RECURSIVE INCLUDE
1626                 //This is not sufficient, since recursive includes could be downstream.
1627                 if (buf && buf != this)
1628                         return buf->getMasterBuffer();
1629         }
1630
1631         return this;
1632 }
1633
1634
1635 Buffer * Buffer::getMasterBuffer()
1636 {
1637         if (!params().parentname.empty()
1638             && theBufferList().exists(params().parentname)) {
1639                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1640                 if (buf)
1641                         return buf->getMasterBuffer();
1642         }
1643
1644         return this;
1645 }
1646
1647
1648 MacroData const & Buffer::getMacro(docstring const & name) const
1649 {
1650         return pimpl_->macros.get(name);
1651 }
1652
1653
1654 bool Buffer::hasMacro(docstring const & name) const
1655 {
1656         return pimpl_->macros.has(name);
1657 }
1658
1659
1660 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1661 {
1662         MacroTable::globalMacros().insert(name, data);
1663         pimpl_->macros.insert(name, data);
1664 }
1665
1666
1667 void Buffer::buildMacros()
1668 {
1669         // Start with global table.
1670         pimpl_->macros = MacroTable::globalMacros();
1671
1672         // Now add our own.
1673         ParagraphList const & pars = text().paragraphs();
1674         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1675                 //lyxerr << "searching main par " << i
1676                 //      << " for macro definitions" << std::endl;
1677                 InsetList const & insets = pars[i].insetlist;
1678                 InsetList::const_iterator it = insets.begin();
1679                 InsetList::const_iterator end = insets.end();
1680                 for ( ; it != end; ++it) {
1681                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1682                         if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1683                                 MathMacroTemplate const & mac
1684                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1685                                 insertMacro(mac.name(), mac.asMacroData());
1686                         }
1687                 }
1688         }
1689 }
1690
1691
1692 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1693 {
1694         cursor_ = cur;
1695         anchor_ = anc;
1696 }
1697
1698
1699 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1700         Inset::Code code)
1701 {
1702         //FIXME: This does not work for child documents yet.
1703         BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1704         // Check if the label 'from' appears more than once
1705         vector<docstring> labels;
1706
1707         if (code == Inset::CITE_CODE) {
1708                 vector<pair<string, docstring> > keys;
1709                 fillWithBibKeys(keys);
1710                 vector<pair<string, docstring> >::const_iterator bit  = keys.begin();
1711                 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1712
1713                 for (; bit != bend; ++bit)
1714                         // FIXME UNICODE
1715                         labels.push_back(from_utf8(bit->first));
1716         } else
1717                 getLabelList(labels);
1718
1719         if (lyx::count(labels.begin(), labels.end(), from) > 1)
1720                 return;
1721
1722         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1723                 if (it->lyxCode() == code) {
1724                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1725                         inset.replaceContents(to_utf8(from), to_utf8(to));
1726                 }
1727         }
1728 }
1729
1730
1731 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1732         pit_type par_end, bool full_source)
1733 {
1734         OutputParams runparams(&params().encoding());
1735         runparams.nice = true;
1736         runparams.flavor = OutputParams::LATEX;
1737         runparams.linelen = lyxrc.plaintext_linelen;
1738         // No side effect of file copying and image conversion
1739         runparams.dryrun = true;
1740
1741         if (full_source) {
1742                 os << "% Preview source code\n\n";
1743                 if (isLatex())
1744                         writeLaTeXSource(os, filePath(), runparams, true, true);
1745                 else {
1746                         writeDocBookSource(os, fileName(), runparams, false);
1747                 }
1748         } else {
1749                 runparams.par_begin = par_begin;
1750                 runparams.par_end = par_end;
1751                 if (par_begin + 1 == par_end)
1752                         os << "% Preview source code for paragraph " << par_begin << "\n\n";
1753                 else
1754                         os << "% Preview source code from paragraph " << par_begin
1755                            << " to " << par_end - 1 << "\n\n";
1756                 // output paragraphs
1757                 if (isLatex()) {
1758                         texrow().reset();
1759                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1760                 } else {
1761                         // DocBook
1762                         docbookParagraphs(paragraphs(), *this, os, runparams);
1763                 }
1764         }
1765 }
1766
1767
1768 ErrorList const & Buffer::errorList(string const & type) const
1769 {
1770         static ErrorList const emptyErrorList;
1771         std::map<string, ErrorList>::const_iterator I = errorLists_.find(type);
1772         if (I == errorLists_.end())
1773                 return emptyErrorList;
1774
1775         return I->second;
1776 }
1777
1778
1779 ErrorList & Buffer::errorList(string const & type)
1780 {
1781         return errorLists_[type];
1782 }
1783
1784
1785 } // namespace lyx