]> git.lyx.org Git - lyx.git/blob - src/buffer.C
the convert patch
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
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 "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "counters.h"
20 #include "Bullet.h"
21 #include "Chktex.h"
22 #include "debug.h"
23 #include "encoding.h"
24 #include "errorlist.h"
25 #include "exporter.h"
26 #include "format.h"
27 #include "funcrequest.h"
28 #include "gettext.h"
29 #include "insetiterator.h"
30 #include "language.h"
31 #include "LaTeX.h"
32 #include "LaTeXFeatures.h"
33 #include "LyXAction.h"
34 #include "lyxlex.h"
35 #include "lyxtext.h"
36 #include "lyxrc.h"
37 #include "lyxvc.h"
38 #include "lyx_main.h"
39 #include "messages.h"
40 #include "output.h"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "output_linuxdoc.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 "undo.h"
51 #include "version.h"
52
53 #include "insets/insetbibitem.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetinclude.h"
56 #include "insets/insettext.h"
57
58 #include "mathed/math_macrotemplate.h"
59 #include "mathed/math_macrotable.h"
60 #include "mathed/math_support.h"
61
62 #include "frontends/Alert.h"
63
64 #include "graphics/Previews.h"
65
66 #include "support/FileInfo.h"
67 #include "support/filetools.h"
68 #ifdef USE_COMPRESSION
69 # include "support/gzstream.h"
70 #endif
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/bind.hpp>
78
79 #include <utime.h>
80
81 #include <iomanip>
82 #include <stack>
83 #include <sstream>
84 #include <fstream>
85
86
87 using lyx::pos_type;
88 using lyx::pit_type;
89
90 using lyx::support::AddName;
91 using lyx::support::bformat;
92 using lyx::support::ChangeExtension;
93 using lyx::support::cmd_ret;
94 using lyx::support::createBufferTmpDir;
95 using lyx::support::destroyDir;
96 using lyx::support::FileInfo;
97 using lyx::support::FileInfo;
98 using lyx::support::getFormatFromContents;
99 using lyx::support::IsDirWriteable;
100 using lyx::support::IsFileWriteable;
101 using lyx::support::LibFileSearch;
102 using lyx::support::ltrim;
103 using lyx::support::MakeAbsPath;
104 using lyx::support::MakeDisplayPath;
105 using lyx::support::MakeLatexName;
106 using lyx::support::OnlyFilename;
107 using lyx::support::OnlyPath;
108 using lyx::support::Path;
109 using lyx::support::QuoteName;
110 using lyx::support::removeAutosaveFile;
111 using lyx::support::rename;
112 using lyx::support::RunCommand;
113 using lyx::support::split;
114 using lyx::support::subst;
115 using lyx::support::tempName;
116 using lyx::support::trim;
117
118 namespace os = lyx::support::os;
119
120 using std::endl;
121 using std::for_each;
122 using std::make_pair;
123
124 using std::ifstream;
125 using std::ios;
126 using std::map;
127 using std::ostream;
128 using std::ostringstream;
129 using std::ofstream;
130 using std::pair;
131 using std::stack;
132 using std::vector;
133 using std::string;
134
135
136 // all these externs should eventually be removed.
137 extern BufferList bufferlist;
138
139 namespace {
140
141 int const LYX_FORMAT = 240;
142
143 } // namespace anon
144
145
146 typedef std::map<string, bool> DepClean;
147
148 class Buffer::Impl
149 {
150 public:
151         Impl(Buffer & parent, string const & file, bool readonly);
152
153         limited_stack<Undo> undostack;
154         limited_stack<Undo> redostack;
155         BufferParams params;
156         LyXVC lyxvc;
157         string temppath;
158         TexRow texrow;
159
160         /// need to regenerate .tex?
161         DepClean dep_clean;
162
163         /// is save needed?
164         mutable bool lyx_clean;
165
166         /// is autosave needed?
167         mutable bool bak_clean;
168
169         /// is this a unnamed file (New...)?
170         bool unnamed;
171
172         /// buffer is r/o
173         bool read_only;
174
175         /// name of the file the buffer is associated with.
176         string filename;
177
178         /// The path to the document file.
179         string filepath;
180
181         boost::scoped_ptr<Messages> messages;
182
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.
186          */
187         bool file_fully_loaded;
188
189         /// our LyXText that should be wrapped in an InsetText
190         InsetText inset;
191
192         ///
193         MacroTable macros;
194 };
195
196
197 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
198         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
199           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
200                 inset(params)
201 {
202         lyxvc.buffer(&parent);
203         temppath = createBufferTmpDir();
204         // FIXME: And now do something if temppath == string(), because we
205         // assume from now on that temppath points to a valid temp dir.
206         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
207 }
208
209
210 Buffer::Buffer(string const & file, bool ronly)
211         : pimpl_(new Impl(*this, file, ronly))
212 {
213         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
214 }
215
216
217 Buffer::~Buffer()
218 {
219         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
220         // here the buffer should take care that it is
221         // saved properly, before it goes into the void.
222
223         closing();
224
225         if (!temppath().empty() && destroyDir(temppath()) != 0) {
226                 Alert::warning(_("Could not remove temporary directory"),
227                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
228         }
229
230         // Remove any previewed LaTeX snippets associated with this buffer.
231         lyx::graphics::Previews::get().removeLoader(*this);
232 }
233
234
235 LyXText & Buffer::text() const
236 {
237         return const_cast<LyXText &>(pimpl_->inset.text_);
238 }
239
240
241 InsetBase & Buffer::inset() const
242 {
243         return const_cast<InsetText &>(pimpl_->inset);
244 }
245
246
247 limited_stack<Undo> & Buffer::undostack()
248 {
249         return pimpl_->undostack;
250 }
251
252
253 limited_stack<Undo> const & Buffer::undostack() const
254 {
255         return pimpl_->undostack;
256 }
257
258
259 limited_stack<Undo> & Buffer::redostack()
260 {
261         return pimpl_->redostack;
262 }
263
264
265 limited_stack<Undo> const & Buffer::redostack() const
266 {
267         return pimpl_->redostack;
268 }
269
270
271 BufferParams & Buffer::params()
272 {
273         return pimpl_->params;
274 }
275
276
277 BufferParams const & Buffer::params() const
278 {
279         return pimpl_->params;
280 }
281
282
283 ParagraphList & Buffer::paragraphs()
284 {
285         return text().paragraphs();
286 }
287
288
289 ParagraphList const & Buffer::paragraphs() const
290 {
291         return text().paragraphs();
292 }
293
294
295 LyXVC & Buffer::lyxvc()
296 {
297         return pimpl_->lyxvc;
298 }
299
300
301 LyXVC const & Buffer::lyxvc() const
302 {
303         return pimpl_->lyxvc;
304 }
305
306
307 string const & Buffer::temppath() const
308 {
309         return pimpl_->temppath;
310 }
311
312
313 TexRow & Buffer::texrow()
314 {
315         return pimpl_->texrow;
316 }
317
318
319 TexRow const & Buffer::texrow() const
320 {
321         return pimpl_->texrow;
322 }
323
324
325 string const Buffer::getLatexName(bool const no_path) const
326 {
327         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
328         return no_path ? OnlyFilename(name) : name;
329 }
330
331
332 pair<Buffer::LogType, string> const Buffer::getLogName() const
333 {
334         string const filename = getLatexName(false);
335
336         if (filename.empty())
337                 return make_pair(Buffer::latexlog, string());
338
339         string const path = temppath();
340
341         string const fname = AddName(path,
342                                      OnlyFilename(ChangeExtension(filename,
343                                                                   ".log")));
344         string const bname =
345                 AddName(path, OnlyFilename(
346                         ChangeExtension(filename,
347                                         formats.extension("literate") + ".out")));
348
349         // If no Latex log or Build log is newer, show Build log
350
351         FileInfo const f_fi(fname);
352         FileInfo const b_fi(bname);
353
354         if (b_fi.exist() &&
355             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
356                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
357                 return make_pair(Buffer::buildlog, bname);
358         }
359         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
360         return make_pair(Buffer::latexlog, fname);
361 }
362
363
364 void Buffer::setReadonly(bool const flag)
365 {
366         if (pimpl_->read_only != flag) {
367                 pimpl_->read_only = flag;
368                 readonly(flag);
369         }
370 }
371
372
373 void Buffer::setFileName(string const & newfile)
374 {
375         pimpl_->filename = MakeAbsPath(newfile);
376         pimpl_->filepath = OnlyPath(pimpl_->filename);
377         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
378         updateTitles();
379 }
380
381
382 // We'll remove this later. (Lgb)
383 namespace {
384
385 void unknownClass(string const & unknown)
386 {
387         Alert::warning(_("Unknown document class"),
388                 bformat(_("Using the default document class, because the "
389                         "class %1$s is unknown."), unknown));
390 }
391
392 } // anon
393
394
395 int Buffer::readHeader(LyXLex & lex)
396 {
397         int unknown_tokens = 0;
398         int line = -1;
399         int begin_header_line = -1;
400
401         while (lex.isOK()) {
402                 lex.next();
403                 string const token = lex.getString();
404
405                 if (token.empty())
406                         continue;
407
408                 if (token == "\\end_header")
409                         break;
410
411                 ++line;
412                 if (token == "\\begin_header") {
413                         begin_header_line = line;
414                         continue;
415                 }
416
417                 lyxerr[Debug::PARSER] << "Handling header token: `"
418                                       << token << '\'' << endl;
419
420                 string unknown = params().readToken(lex, token);
421                 if (!unknown.empty()) {
422                         if (unknown[0] != '\\' && token == "\\textclass") {
423                                 unknownClass(unknown);
424                         } else {
425                                 ++unknown_tokens;
426                                 string const s = bformat(_("Unknown token: "
427                                                            "%1$s %2$s\n"),
428                                                          token,
429                                                          lex.getString());
430                                 error(ErrorItem(_("Header error"), s,
431                                                 -1, 0, 0));
432                         }
433                 }
434         }
435         if (begin_header_line) {
436                 string const s = _("\\begin_header is missing");
437                 error(ErrorItem(_("Header error"), s, -1, 0, 0));
438         }
439         return unknown_tokens;
440 }
441
442
443 // Uwe C. Schroeder
444 // changed to be public and have one parameter
445 // Returns false if "\end_document" is not read (Asger)
446 bool Buffer::readDocument(LyXLex & lex)
447 {
448         lex.next();
449         string const token = lex.getString();
450         if (token != "\\begin_document") {
451                 string const s = _("\\begin_document is missing");
452                 error(ErrorItem(_("Header error"), s, -1, 0, 0));
453         }
454
455         if (paragraphs().empty()) {
456                 readHeader(lex);
457                 if (!params().getLyXTextClass().load()) {
458                         string theclass = params().getLyXTextClass().name();
459                         Alert::error(_("Can't load document class"), bformat(
460                                         "Using the default document class, because the "
461                                         " class %1$s could not be loaded.", theclass));
462                         params().textclass = 0;
463                 }
464         } else {
465                 // We don't want to adopt the parameters from the
466                 // document we insert, so read them into a temporary buffer
467                 // and then discard it
468
469                 Buffer tmpbuf("", false);
470                 tmpbuf.readHeader(lex);
471         }
472
473         return text().read(*this, lex);
474 }
475
476
477 // needed to insert the selection
478 void Buffer::insertStringAsLines(ParagraphList & pars,
479         pit_type & par, pos_type & pos,
480         LyXFont const & fn, string const & str, bool autobreakrows)
481 {
482         LyXLayout_ptr const & layout = pars[par].layout();
483
484         LyXFont font = fn;
485
486         pars[par].checkInsertChar(font);
487         // insert the string, don't insert doublespace
488         bool space_inserted = true;
489         for (string::const_iterator cit = str.begin();
490             cit != str.end(); ++cit) {
491                 if (*cit == '\n') {
492                         if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
493                                 breakParagraph(params(), paragraphs(), par, pos,
494                                                layout->isEnvironment());
495                                 ++par;
496                                 pos = 0;
497                                 space_inserted = true;
498                         } else {
499                                 continue;
500                         }
501                         // do not insert consecutive spaces if !free_spacing
502                 } else if ((*cit == ' ' || *cit == '\t') &&
503                            space_inserted && !pars[par].isFreeSpacing()) {
504                         continue;
505                 } else if (*cit == '\t') {
506                         if (!pars[par].isFreeSpacing()) {
507                                 // tabs are like spaces here
508                                 pars[par].insertChar(pos, ' ', font);
509                                 ++pos;
510                                 space_inserted = true;
511                         } else {
512                                 const pos_type n = 8 - pos % 8;
513                                 for (pos_type i = 0; i < n; ++i) {
514                                         pars[par].insertChar(pos, ' ', font);
515                                         ++pos;
516                                 }
517                                 space_inserted = true;
518                         }
519                 } else if (!IsPrintable(*cit)) {
520                         // Ignore unprintables
521                         continue;
522                 } else {
523                         // just insert the character
524                         pars[par].insertChar(pos, *cit, font);
525                         ++pos;
526                         space_inserted = (*cit == ' ');
527                 }
528
529         }
530 }
531
532
533 bool Buffer::readFile(string const & filename)
534 {
535         // Check if the file is compressed.
536         string const format = getFormatFromContents(filename);
537         if (format == "gzip" || format == "zip" || format == "compress") {
538                 params().compressed = true;
539         }
540
541         // remove dummy empty par
542         paragraphs().clear();
543         bool ret = readFile(filename, paragraphs().size());
544
545         // After we have read a file, we must ensure that the buffer
546         // language is set and used in the gui.
547         // If you know of a better place to put this, please tell me. (Lgb)
548         updateDocLang(params().language);
549
550         return ret;
551 }
552
553
554 bool Buffer::readFile(string const & filename, pit_type const pit)
555 {
556         LyXLex lex(0, 0);
557         lex.setFile(filename);
558         return readFile(lex, filename, pit);
559 }
560
561
562 bool Buffer::fully_loaded() const
563 {
564         return pimpl_->file_fully_loaded;
565 }
566
567
568 void Buffer::fully_loaded(bool const value)
569 {
570         pimpl_->file_fully_loaded = value;
571 }
572
573
574 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
575 {
576         BOOST_ASSERT(!filename.empty());
577
578         if (!lex.isOK()) {
579                 Alert::error(_("Document could not be read"),
580                              bformat(_("%1$s could not be read."), filename));
581                 return false;
582         }
583
584         lex.next();
585         string const token(lex.getString());
586
587         if (!lex.isOK()) {
588                 Alert::error(_("Document could not be read"),
589                              bformat(_("%1$s could not be read."), filename));
590                 return false;
591         }
592
593         // the first token _must_ be...
594         if (token != "\\lyxformat") {
595                 lyxerr << "Token: " << token << endl;
596
597                 Alert::error(_("Document format failure"),
598                              bformat(_("%1$s is not a LyX document."),
599                                        filename));
600                 return false;
601         }
602
603         lex.next();
604         string tmp_format = lex.getString();
605         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
606         // if present remove ".," from string.
607         string::size_type dot = tmp_format.find_first_of(".,");
608         //lyxerr << "           dot found at " << dot << endl;
609         if (dot != string::npos)
610                         tmp_format.erase(dot, 1);
611         int const file_format = convert<int>(tmp_format);
612         //lyxerr << "format: " << file_format << endl;
613
614         if (file_format != LYX_FORMAT) {
615                 string const tmpfile = tempName();
616                 if (tmpfile.empty()) {
617                         Alert::error(_("Conversion failed"),
618                                      bformat(_("%1$s is from an earlier"
619                                               " version of LyX, but a temporary"
620                                               " file for converting it could"
621                                               " not be created."),
622                                               filename));
623                         return false;
624                 }
625                 string command =
626                         "python " + LibFileSearch("lyx2lyx", "lyx2lyx");
627                 if (command.empty()) {
628                         Alert::error(_("Conversion script not found"),
629                                      bformat(_("%1$s is from an earlier"
630                                                " version of LyX, but the"
631                                                " conversion script lyx2lyx"
632                                                " could not be found."),
633                                                filename));
634                         return false;
635                 }
636                 command += " -t"
637                         + convert<string>(LYX_FORMAT)
638                         + " -o " + tmpfile + ' '
639                         + QuoteName(filename);
640                 lyxerr[Debug::INFO] << "Running '"
641                                     << command << '\''
642                                     << endl;
643                 cmd_ret const ret = RunCommand(command);
644                 if (ret.first != 0) {
645                         Alert::error(_("Conversion script failed"),
646                                      bformat(_("%1$s is from an earlier version"
647                                               " of LyX, but the lyx2lyx script"
648                                               " failed to convert it."),
649                                               filename));
650                         return false;
651                 } else {
652                         bool const ret = readFile(tmpfile, pit);
653                         // Do stuff with tmpfile name and buffer name here.
654                         return ret;
655                 }
656
657         }
658
659         if (readDocument(lex)) {
660                 Alert::error(_("Document format failure"),
661                              bformat(_("%1$s ended unexpectedly, which means"
662                                        " that it is probably corrupted."),
663                                        filename));
664         }
665
666         //lyxerr << "removing " << MacroTable::localMacros().size()
667         //      << " temporary macro entries" << endl;
668         //MacroTable::localMacros().clear();
669         params().setPaperStuff();
670
671         pimpl_->file_fully_loaded = true;
672         return true;
673 }
674
675
676 // Should probably be moved to somewhere else: BufferView? LyXView?
677 bool Buffer::save() const
678 {
679         // We don't need autosaves in the immediate future. (Asger)
680         resetAutosaveTimers();
681
682         // make a backup
683         string s;
684         if (lyxrc.make_backup) {
685                 s = fileName() + '~';
686                 if (!lyxrc.backupdir_path.empty())
687                         s = AddName(lyxrc.backupdir_path,
688                                     subst(os::internal_path(s),'/','!'));
689
690                 // Rename is the wrong way of making a backup,
691                 // this is the correct way.
692                 /* truss cp fil fil2:
693                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
694                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
695                    open("LyXVC.lyx", O_RDONLY)                     = 3
696                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
697                    fstat(4, 0xEFFFF508)                            = 0
698                    fstat(3, 0xEFFFF508)                            = 0
699                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
700                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
701                    read(3, 0xEFFFD4A0, 8192)                       = 0
702                    close(4)                                        = 0
703                    close(3)                                        = 0
704                    chmod("LyXVC3.lyx", 0100644)                    = 0
705                    lseek(0, 0, SEEK_CUR)                           = 46440
706                    _exit(0)
707                 */
708
709                 // Should probably have some more error checking here.
710                 // Doing it this way, also makes the inodes stay the same.
711                 // This is still not a very good solution, in particular we
712                 // might loose the owner of the backup.
713                 FileInfo finfo(fileName());
714                 if (finfo.exist()) {
715                         mode_t fmode = finfo.getMode();
716                         struct utimbuf times = {
717                                 finfo.getAccessTime(),
718                                 finfo.getModificationTime() };
719
720                         ifstream ifs(fileName().c_str());
721                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
722                         if (ifs && ofs) {
723                                 ofs << ifs.rdbuf();
724                                 ifs.close();
725                                 ofs.close();
726                                 ::chmod(s.c_str(), fmode);
727
728                                 if (::utime(s.c_str(), &times)) {
729                                         lyxerr << "utime error." << endl;
730                                 }
731                         } else {
732                                 lyxerr << "LyX was not able to make "
733                                         "backup copy. Beware." << endl;
734                         }
735                 }
736         }
737
738         if (writeFile(fileName())) {
739                 markClean();
740                 removeAutosaveFile(fileName());
741         } else {
742                 // Saving failed, so backup is not backup
743                 if (lyxrc.make_backup)
744                         rename(s, fileName());
745                 return false;
746         }
747         return true;
748 }
749
750
751 bool Buffer::writeFile(string const & fname) const
752 {
753         if (pimpl_->read_only && fname == fileName())
754                 return false;
755
756         FileInfo finfo(fname);
757         if (finfo.exist() && !finfo.writable())
758                 return false;
759
760         bool retval = false;
761
762         if (params().compressed) {
763 #ifdef USE_COMPRESSION
764                 gz::ogzstream ofs(fname.c_str());
765                 if (!ofs)
766                         return false;
767
768                 retval = do_writeFile(ofs);
769 #else
770                 return false;
771 #endif
772         } else {
773                 ofstream ofs(fname.c_str());
774                 if (!ofs)
775                         return false;
776
777                 retval = do_writeFile(ofs);
778         }
779
780         return retval;
781 }
782
783
784 bool Buffer::do_writeFile(ostream & ofs) const
785 {
786 #ifdef HAVE_LOCALE
787         // Use the standard "C" locale for file output.
788         ofs.imbue(std::locale::classic());
789 #endif
790
791         // The top of the file should not be written by params().
792
793         // write out a comment in the top of the file
794         ofs << "#LyX " << lyx_version
795             << " created this file. For more info see http://www.lyx.org/\n"
796             << "\\lyxformat " << LYX_FORMAT << "\n"
797             << "\\begin_document\n";
798
799         // now write out the buffer parameters.
800         ofs << "\\begin_header\n";
801         params().writeFile(ofs);
802         ofs << "\\end_header\n";
803
804         // write the text
805         ofs << "\n\\begin_body\n";
806         text().write(*this, ofs);
807         ofs << "\n\\end_body\n";
808
809         // Write marker that shows file is complete
810         ofs << "\\end_document" << endl;
811
812         // Shouldn't really be needed....
813         //ofs.close();
814
815         // how to check if close went ok?
816         // Following is an attempt... (BE 20001011)
817
818         // good() returns false if any error occured, including some
819         //        formatting error.
820         // bad()  returns true if something bad happened in the buffer,
821         //        which should include file system full errors.
822
823         bool status = true;
824         if (!ofs) {
825                 status = false;
826                 lyxerr << "File was not closed properly." << endl;
827         }
828
829         return status;
830 }
831
832
833 void Buffer::makeLaTeXFile(string const & fname,
834                            string const & original_path,
835                            OutputParams const & runparams,
836                            bool output_preamble, bool output_body)
837 {
838         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
839
840         ofstream ofs;
841         if (!openFileWrite(ofs, fname))
842                 return;
843
844         makeLaTeXFile(ofs, original_path,
845                       runparams, output_preamble, output_body);
846
847         ofs.close();
848         if (ofs.fail())
849                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
850 }
851
852
853 void Buffer::makeLaTeXFile(ostream & os,
854                            string const & original_path,
855                            OutputParams const & runparams_in,
856                            bool const output_preamble, bool const output_body)
857 {
858         OutputParams runparams = runparams_in;
859
860         // validate the buffer.
861         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
862         LaTeXFeatures features(*this, params(), runparams.nice);
863         validate(features);
864         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
865
866         texrow().reset();
867
868         // The starting paragraph of the coming rows is the
869         // first paragraph of the document. (Asger)
870         texrow().start(paragraphs().begin()->id(), 0);
871
872         if (output_preamble && runparams.nice) {
873                 os << "%% LyX " << lyx_version << " created this file.  "
874                         "For more info, see http://www.lyx.org/.\n"
875                         "%% Do not edit unless you really know what "
876                         "you are doing.\n";
877                 texrow().newline();
878                 texrow().newline();
879         }
880         lyxerr[Debug::INFO] << "lyx header finished" << endl;
881         // There are a few differences between nice LaTeX and usual files:
882         // usual is \batchmode and has a
883         // special input@path to allow the including of figures
884         // with either \input or \includegraphics (what figinsets do).
885         // input@path is set when the actual parameter
886         // original_path is set. This is done for usual tex-file, but not
887         // for nice-latex-file. (Matthias 250696)
888         // Note that input@path is only needed for something the user does
889         // in the preamble, included .tex files or ERT, files included by
890         // LyX work without it.
891         if (output_preamble) {
892                 if (!runparams.nice) {
893                         // code for usual, NOT nice-latex-file
894                         os << "\\batchmode\n"; // changed
895                         // from \nonstopmode
896                         texrow().newline();
897                 }
898                 if (!original_path.empty()) {
899                         string inputpath = os::external_path(original_path);
900                         subst(inputpath, "~", "\\string~");
901                         os << "\\makeatletter\n"
902                             << "\\def\\input@path{{"
903                             << inputpath << "/}}\n"
904                             << "\\makeatother\n";
905                         texrow().newline();
906                         texrow().newline();
907                         texrow().newline();
908                 }
909
910                 // Write the preamble
911                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
912
913                 if (!output_body)
914                         return;
915
916                 // make the body.
917                 os << "\\begin{document}\n";
918                 texrow().newline();
919         } // output_preamble
920         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
921
922         if (!lyxrc.language_auto_begin) {
923                 os << subst(lyxrc.language_command_begin, "$$lang",
924                              params().language->babel())
925                     << endl;
926                 texrow().newline();
927         }
928
929         // if we are doing a real file with body, even if this is the
930         // child of some other buffer, let's cut the link here.
931         // This happens for example if only a child document is printed.
932         string save_parentname;
933         if (output_preamble) {
934                 save_parentname = params().parentname;
935                 params().parentname.erase();
936         }
937
938         // the real stuff
939         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
940
941         // Restore the parenthood if needed
942         if (output_preamble)
943                 params().parentname = save_parentname;
944
945         // add this just in case after all the paragraphs
946         os << endl;
947         texrow().newline();
948
949         if (!lyxrc.language_auto_end) {
950                 os << subst(lyxrc.language_command_end, "$$lang",
951                              params().language->babel())
952                     << endl;
953                 texrow().newline();
954         }
955
956         if (output_preamble) {
957                 os << "\\end{document}\n";
958                 texrow().newline();
959
960                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
961         } else {
962                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
963                                      << endl;
964         }
965
966         // Just to be sure. (Asger)
967         texrow().newline();
968
969         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
970         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
971                             << '.' << endl;
972 }
973
974
975 bool Buffer::isLatex() const
976 {
977         return params().getLyXTextClass().outputType() == LATEX;
978 }
979
980
981 bool Buffer::isLinuxDoc() const
982 {
983         return params().getLyXTextClass().outputType() == LINUXDOC;
984 }
985
986
987 bool Buffer::isLiterate() const
988 {
989         return params().getLyXTextClass().outputType() == LITERATE;
990 }
991
992
993 bool Buffer::isDocBook() const
994 {
995         return params().getLyXTextClass().outputType() == DOCBOOK;
996 }
997
998
999 bool Buffer::isSGML() const
1000 {
1001         LyXTextClass const & tclass = params().getLyXTextClass();
1002
1003         return tclass.outputType() == LINUXDOC ||
1004                tclass.outputType() == DOCBOOK;
1005 }
1006
1007
1008 void Buffer::makeLinuxDocFile(string const & fname,
1009                               OutputParams const & runparams,
1010                               bool const body_only)
1011 {
1012         ofstream ofs;
1013         if (!openFileWrite(ofs, fname))
1014                 return;
1015
1016         LaTeXFeatures features(*this, params(), runparams.nice);
1017         validate(features);
1018
1019         texrow().reset();
1020
1021         LyXTextClass const & tclass = params().getLyXTextClass();
1022
1023         string const & top_element = tclass.latexname();
1024
1025         if (!body_only) {
1026                 ofs << tclass.class_header();
1027
1028                 string preamble = params().preamble;
1029                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1030                          : fname;
1031                 preamble += features.getIncludedFiles(name);
1032                 preamble += features.getLyXSGMLEntities();
1033
1034                 if (!preamble.empty()) {
1035                         ofs << " [ " << preamble << " ]";
1036                 }
1037                 ofs << ">\n\n";
1038
1039                 if (params().options.empty())
1040                         sgml::openTag(ofs, top_element);
1041                 else {
1042                         string top = top_element;
1043                         top += ' ';
1044                         top += params().options;
1045                         sgml::openTag(ofs, top);
1046                 }
1047         }
1048
1049         ofs << "<!-- LyX "  << lyx_version
1050             << " created this file. For more info see http://www.lyx.org/"
1051             << " -->\n";
1052
1053         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1054
1055         if (!body_only) {
1056                 ofs << "\n\n";
1057                 sgml::closeTag(ofs, top_element);
1058         }
1059
1060         ofs.close();
1061         if (ofs.fail())
1062                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1063 }
1064
1065
1066 void Buffer::makeDocBookFile(string const & fname,
1067                              OutputParams const & runparams,
1068                              bool const only_body)
1069 {
1070         ofstream ofs;
1071         if (!openFileWrite(ofs, fname))
1072                 return;
1073
1074         LaTeXFeatures features(*this, params(), runparams.nice);
1075         validate(features);
1076
1077         texrow().reset();
1078
1079         LyXTextClass const & tclass = params().getLyXTextClass();
1080         string const & top_element = tclass.latexname();
1081
1082         if (!only_body) {
1083                 if (runparams.flavor == OutputParams::XML)
1084                         ofs << "<?xml version=\"1.0\" encoding=\""
1085                             << params().language->encoding()->Name() << "\"?>\n";
1086
1087                 ofs << "<!DOCTYPE " << top_element << " ";
1088
1089                 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1090                 else if (runparams.flavor == OutputParams::XML)
1091                         ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1092                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1093                 else
1094                         ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1095
1096                 string preamble = params().preamble;
1097                 if (runparams.flavor != OutputParams::XML ) {
1098                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1099                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1100                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1101                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1102                 }
1103
1104                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1105                          : fname;
1106                 preamble += features.getIncludedFiles(name);
1107                 preamble += features.getLyXSGMLEntities();
1108
1109                 if (!preamble.empty()) {
1110                         ofs << "\n [ " << preamble << " ]";
1111                 }
1112                 ofs << ">\n\n";
1113         }
1114
1115         string top = top_element;
1116         top += " lang=\"";
1117         if (runparams.flavor == OutputParams::XML)
1118                 top += params().language->code();
1119         else
1120                 top += params().language->code().substr(0,2);
1121         top += '"';
1122
1123         if (!params().options.empty()) {
1124                 top += ' ';
1125                 top += params().options;
1126         }
1127
1128         ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1129             << " file was created by LyX " << lyx_version
1130             << "\n  See http://www.lyx.org/ for more information -->\n";
1131
1132         params().getLyXTextClass().counters().reset();
1133
1134         sgml::openTag(ofs, top);
1135         ofs << '\n';
1136         docbookParagraphs(paragraphs(), *this, ofs, runparams);
1137         sgml::closeTag(ofs, top_element);
1138
1139         ofs.close();
1140         if (ofs.fail())
1141                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1142 }
1143
1144
1145 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1146 // Other flags: -wall -v0 -x
1147 int Buffer::runChktex()
1148 {
1149         busy(true);
1150
1151         // get LaTeX-Filename
1152         string const name = getLatexName();
1153         string const path = temppath();
1154         string const org_path = filePath();
1155
1156         Path p(path); // path to LaTeX file
1157         message(_("Running chktex..."));
1158
1159         // Generate the LaTeX file if neccessary
1160         OutputParams runparams;
1161         runparams.flavor = OutputParams::LATEX;
1162         runparams.nice = false;
1163         makeLaTeXFile(name, org_path, runparams);
1164
1165         TeXErrors terr;
1166         Chktex chktex(lyxrc.chktex_command, name, filePath());
1167         int const res = chktex.run(terr); // run chktex
1168
1169         if (res == -1) {
1170                 Alert::error(_("chktex failure"),
1171                              _("Could not run chktex successfully."));
1172         } else if (res > 0) {
1173                 // Insert all errors as errors boxes
1174                 bufferErrors(*this, terr);
1175         }
1176
1177         busy(false);
1178
1179         return res;
1180 }
1181
1182
1183 void Buffer::validate(LaTeXFeatures & features) const
1184 {
1185         LyXTextClass const & tclass = params().getLyXTextClass();
1186
1187         if (features.isAvailable("dvipost") && params().tracking_changes
1188                 && params().output_changes) {
1189                 features.require("dvipost");
1190                 features.require("color");
1191         }
1192
1193         // AMS Style is at document level
1194         if (params().use_amsmath == BufferParams::AMS_ON
1195             || tclass.provides(LyXTextClass::amsmath))
1196                 features.require("amsmath");
1197
1198         for_each(paragraphs().begin(), paragraphs().end(),
1199                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1200
1201         // the bullet shapes are buffer level not paragraph level
1202         // so they are tested here
1203         for (int i = 0; i < 4; ++i) {
1204                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1205                         int const font = params().user_defined_bullet(i).getFont();
1206                         if (font == 0) {
1207                                 int const c = params()
1208                                         .user_defined_bullet(i)
1209                                         .getCharacter();
1210                                 if (c == 16
1211                                    || c == 17
1212                                    || c == 25
1213                                    || c == 26
1214                                    || c == 31) {
1215                                         features.require("latexsym");
1216                                 }
1217                         } else if (font == 1) {
1218                                 features.require("amssymb");
1219                         } else if ((font >= 2 && font <= 5)) {
1220                                 features.require("pifont");
1221                         }
1222                 }
1223         }
1224
1225         if (lyxerr.debugging(Debug::LATEX)) {
1226                 features.showStruct();
1227         }
1228 }
1229
1230
1231 void Buffer::getLabelList(vector<string> & list) const
1232 {
1233         /// if this is a child document and the parent is already loaded
1234         /// Use the parent's list instead  [ale990407]
1235         Buffer const * tmp = getMasterBuffer();
1236         if (!tmp) {
1237                 lyxerr << "getMasterBuffer() failed!" << endl;
1238                 BOOST_ASSERT(tmp);
1239         }
1240         if (tmp != this) {
1241                 tmp->getLabelList(list);
1242                 return;
1243         }
1244
1245         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1246                 it.nextInset()->getLabelList(*this, list);
1247 }
1248
1249
1250 // This is also a buffer property (ale)
1251 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1252         const
1253 {
1254         /// if this is a child document and the parent is already loaded
1255         /// use the parent's list instead  [ale990412]
1256         Buffer const * tmp = getMasterBuffer();
1257         BOOST_ASSERT(tmp);
1258         if (tmp != this) {
1259                 tmp->fillWithBibKeys(keys);
1260                 return;
1261         }
1262
1263         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1264                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1265                         InsetBibtex const & inset =
1266                                 dynamic_cast<InsetBibtex const &>(*it);
1267                         inset.fillWithBibKeys(*this, keys);
1268                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1269                         InsetInclude const & inset =
1270                                 dynamic_cast<InsetInclude const &>(*it);
1271                         inset.fillWithBibKeys(*this, keys);
1272                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1273                         InsetBibitem const & inset =
1274                                 dynamic_cast<InsetBibitem const &>(*it);
1275                         string const key = inset.getContents();
1276                         string const opt = inset.getOptions();
1277                         string const ref; // = pit->asString(this, false);
1278                         string const info = opt + "TheBibliographyRef" + ref;
1279                         keys.push_back(pair<string, string>(key, info));
1280                 }
1281         }
1282 }
1283
1284
1285 bool Buffer::isDepClean(string const & name) const
1286 {
1287         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1288         if (it == pimpl_->dep_clean.end())
1289                 return true;
1290         return it->second;
1291 }
1292
1293
1294 void Buffer::markDepClean(string const & name)
1295 {
1296         pimpl_->dep_clean[name] = true;
1297 }
1298
1299
1300 bool Buffer::dispatch(string const & command, bool * result)
1301 {
1302         return dispatch(lyxaction.lookupFunc(command), result);
1303 }
1304
1305
1306 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1307 {
1308         bool dispatched = true;
1309
1310         switch (func.action) {
1311                 case LFUN_EXPORT: {
1312                         bool const tmp = Exporter::Export(this, func.argument, false);
1313                         if (result)
1314                                 *result = tmp;
1315                         break;
1316                 }
1317
1318                 default:
1319                         dispatched = false;
1320         }
1321         return dispatched;
1322 }
1323
1324
1325 void Buffer::changeLanguage(Language const * from, Language const * to)
1326 {
1327         BOOST_ASSERT(from);
1328         BOOST_ASSERT(to);
1329
1330         lyxerr << "Changing Language!" << endl;
1331
1332         // Take care of l10n/i18n
1333         updateDocLang(to);
1334
1335         for_each(par_iterator_begin(),
1336                  par_iterator_end(),
1337                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1338 }
1339
1340
1341 void Buffer::updateDocLang(Language const * nlang)
1342 {
1343         BOOST_ASSERT(nlang);
1344
1345         pimpl_->messages.reset(new Messages(nlang->code()));
1346 }
1347
1348
1349 bool Buffer::isMultiLingual() const
1350 {
1351         ParConstIterator end = par_iterator_end();
1352         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1353                 if (it->isMultiLingual(params()))
1354                         return true;
1355
1356         return false;
1357 }
1358
1359
1360 ParIterator Buffer::getParFromID(int const id) const
1361 {
1362         ParConstIterator it = par_iterator_begin();
1363         ParConstIterator const end = par_iterator_end();
1364
1365         if (id < 0) {
1366                 // John says this is called with id == -1 from undo
1367                 lyxerr << "getParFromID(), id: " << id << endl;
1368                 return end;
1369         }
1370
1371         for (; it != end; ++it)
1372                 if (it->id() == id)
1373                         return it;
1374
1375         return end;
1376 }
1377
1378
1379 bool Buffer::hasParWithID(int const id) const
1380 {
1381         ParConstIterator const it = getParFromID(id);
1382         return it != par_iterator_end();
1383 }
1384
1385
1386 ParIterator Buffer::par_iterator_begin()
1387 {
1388         return ::par_iterator_begin(inset());
1389 }
1390
1391
1392 ParIterator Buffer::par_iterator_end()
1393 {
1394         return ::par_iterator_end(inset());
1395 }
1396
1397
1398 ParConstIterator Buffer::par_iterator_begin() const
1399 {
1400         return ::par_const_iterator_begin(inset());
1401 }
1402
1403
1404 ParConstIterator Buffer::par_iterator_end() const
1405 {
1406         return ::par_const_iterator_end(inset());
1407 }
1408
1409
1410 Language const * Buffer::getLanguage() const
1411 {
1412         return params().language;
1413 }
1414
1415
1416 string const Buffer::B_(string const & l10n) const
1417 {
1418         if (pimpl_->messages.get()) {
1419                 return pimpl_->messages->get(l10n);
1420         }
1421
1422         return _(l10n);
1423 }
1424
1425
1426 bool Buffer::isClean() const
1427 {
1428         return pimpl_->lyx_clean;
1429 }
1430
1431
1432 bool Buffer::isBakClean() const
1433 {
1434         return pimpl_->bak_clean;
1435 }
1436
1437
1438 void Buffer::markClean() const
1439 {
1440         if (!pimpl_->lyx_clean) {
1441                 pimpl_->lyx_clean = true;
1442                 updateTitles();
1443         }
1444         // if the .lyx file has been saved, we don't need an
1445         // autosave
1446         pimpl_->bak_clean = true;
1447 }
1448
1449
1450 void Buffer::markBakClean()
1451 {
1452         pimpl_->bak_clean = true;
1453 }
1454
1455
1456 void Buffer::setUnnamed(bool flag)
1457 {
1458         pimpl_->unnamed = flag;
1459 }
1460
1461
1462 bool Buffer::isUnnamed() const
1463 {
1464         return pimpl_->unnamed;
1465 }
1466
1467
1468 #ifdef WITH_WARNINGS
1469 #warning this function should be moved to buffer_pimpl.C
1470 #endif
1471 void Buffer::markDirty()
1472 {
1473         if (pimpl_->lyx_clean) {
1474                 pimpl_->lyx_clean = false;
1475                 updateTitles();
1476         }
1477         pimpl_->bak_clean = false;
1478
1479         DepClean::iterator it = pimpl_->dep_clean.begin();
1480         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1481
1482         for (; it != end; ++it) {
1483                 it->second = false;
1484         }
1485 }
1486
1487
1488 string const & Buffer::fileName() const
1489 {
1490         return pimpl_->filename;
1491 }
1492
1493
1494 string const & Buffer::filePath() const
1495 {
1496         return pimpl_->filepath;
1497 }
1498
1499
1500 bool Buffer::isReadonly() const
1501 {
1502         return pimpl_->read_only;
1503 }
1504
1505
1506 void Buffer::setParentName(string const & name)
1507 {
1508         params().parentname = name;
1509 }
1510
1511
1512 Buffer const * Buffer::getMasterBuffer() const
1513 {
1514         if (!params().parentname.empty()
1515             && bufferlist.exists(params().parentname)) {
1516                 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1517                 if (buf)
1518                         return buf->getMasterBuffer();
1519         }
1520
1521         return this;
1522 }
1523
1524
1525 MacroData const & Buffer::getMacro(std::string const & name) const
1526 {
1527         return pimpl_->macros.get(name);
1528 }
1529
1530
1531 bool Buffer::hasMacro(string const & name) const
1532 {
1533         return pimpl_->macros.has(name);
1534 }
1535
1536
1537 void Buffer::insertMacro(string const & name, MacroData const & data)
1538 {
1539         MacroTable::globalMacros().insert(name, data);
1540         pimpl_->macros.insert(name, data);
1541 }
1542
1543
1544 void Buffer::buildMacros()
1545 {
1546         // Start with global table.
1547         pimpl_->macros = MacroTable::globalMacros();
1548
1549         // Now add our own.
1550         ParagraphList & pars = text().paragraphs();
1551         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1552                 //lyxerr << "searching main par " << i
1553                 //      << " for macro definitions" << std::endl;
1554                 InsetList::iterator it = pars[i].insetlist.begin();
1555                 InsetList::iterator end = pars[i].insetlist.end();
1556                 for ( ; it != end; ++it) {
1557                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1558                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1559                                 MathMacroTemplate & mac
1560                                         = static_cast<MathMacroTemplate &>(*it->inset);
1561                                 insertMacro(mac.name(), mac.asMacroData());
1562                         }
1563                 }
1564         }
1565 }