]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
* gcc does not like missing characters in keywords
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/FileName.h"
18 #include "support/docstring.h"
19 #include "support/docstream.h"
20 #include "support/types.h"
21
22 #include <iosfwd>
23 #include <string>
24 #include <utility>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BufferParams;
31 class EmbeddedFiles;
32 class ErrorItem;
33 class ErrorList;
34 class FuncRequest;
35 class Inset;
36 class Font;
37 class Format;
38 class Lexer;
39 class LyXRC;
40 class Text;
41 class LyXVC;
42 class LaTeXFeatures;
43 class Language;
44 class MacroData;
45 class OutputParams;
46 class ParConstIterator;
47 class ParIterator;
48 class ParagraphList;
49 class TeXErrors;
50 class TexRow;
51 class TocBackend;
52 class Undo;
53
54 namespace frontend {
55 class GuiBufferDelegate;
56 class WorkAreaManager;
57 }
58
59 /** The buffer object.
60  * This is the buffer object. It contains all the informations about
61  * a document loaded into LyX.
62  * The buffer object owns the Text (wrapped in an InsetText), which
63  * contains the individual paragraphs of the document.
64  *
65  *
66  * I am not sure if the class is complete or
67  * minimal, probably not.
68  * \author Lars Gullik Bjønnes
69  */
70 class Buffer {
71 public:
72         /// What type of log will \c getLogName() return?
73         enum LogType {
74                 latexlog, ///< LaTeX log
75                 buildlog  ///< Literate build log
76         };
77
78         /// Result of \c readFile()
79         enum ReadStatus {
80                 failure, ///< The file could not be read
81                 success, ///< The file could not be read
82                 wrongversion ///< The version of the file does not match ours
83         };
84
85         /// Method to check if a file is externally modified, used by 
86         /// isExternallyModified()
87         /**
88          * timestamp is fast but inaccurate. For example, the granularity
89          * of timestamp on a FAT filesystem is 2 second. Also, various operations
90          * may touch the timestamp of a file even when its content is unchanged.
91          *
92          * checksum is accurate but slow, which can be a problem when it is 
93          * frequently used, or used for a large file on a slow (network) file
94          * system.
95          */
96         enum CheckMethod {
97                 checksum_method,  ///< Use file check sum
98                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
99         };
100         
101         /** Constructor
102             \param file
103             \param b  optional \c false by default
104         */
105         explicit Buffer(std::string const & file, bool b = false);
106
107         /// Destructor
108         ~Buffer();
109
110         /** High-level interface to buffer functionality.
111             This function parses a command string and executes it
112         */
113         bool dispatch(std::string const & command, bool * result = 0);
114
115         /// Maybe we know the function already by number...
116         bool dispatch(FuncRequest const & func, bool * result = 0);
117
118         /// Load the autosaved file.
119         void loadAutoSaveFile();
120
121         /// read a new document from a string
122         bool readString(std::string const &);
123         /// load a new file
124         bool readFile(support::FileName const & filename);
125
126         /// read the header, returns number of unknown tokens
127         int readHeader(Lexer & lex);
128
129         /** Reads a file without header.
130             \param par if != 0 insert the file.
131             \return \c false if file is not completely read.
132         */
133         bool readDocument(Lexer &);
134
135         ///
136         void insertStringAsLines(ParagraphList & plist,
137                 pit_type &, pos_type &,
138                 Font const &, docstring const &, bool);
139         ///
140         ParIterator getParFromID(int id) const;
141         /// do we have a paragraph with this id?
142         bool hasParWithID(int id) const;
143
144         ///
145         frontend::WorkAreaManager & workAreaManager() const;
146
147         /** Save file.
148             Takes care of auto-save files and backup file if requested.
149             Returns \c true if the save is successful, \c false otherwise.
150         */
151         bool save() const;
152
153         /// Write document to stream. Returns \c false if unsuccesful.
154         bool write(std::ostream &) const;
155         /// Write file. Returns \c false if unsuccesful.
156         bool writeFile(support::FileName const &) const;
157
158   /// Loads LyX file \c filename into buffer, *  and \return success 
159         bool loadLyXFile(support::FileName const & s);
160
161         /// Fill in the ErrorList with the TeXErrors
162         void bufferErrors(TeXErrors const &, ErrorList &) const;
163
164         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
165         bool makeLaTeXFile(support::FileName const & filename,
166                            std::string const & original_path,
167                            OutputParams const &,
168                            bool output_preamble = true,
169                            bool output_body = true);
170         /** Export the buffer to LaTeX.
171             If \p os is a file stream, and params().inputenc is "auto" or
172             "default", and the buffer contains text in different languages
173             with more than one encoding, then this method will change the
174             encoding associated to \p os. Therefore you must not call this
175             method with a string stream if the output is supposed to go to a
176             file. \code
177             odocfstream ofs;
178             ofs.open("test.tex");
179             writeLaTeXSource(ofs, ...);
180             ofs.close();
181             \endcode is NOT equivalent to \code
182             odocstringstream oss;
183             writeLaTeXSource(oss, ...);
184             odocfstream ofs;
185             ofs.open("test.tex");
186             ofs << oss.str();
187             ofs.close();
188             \endcode
189          */
190         void writeLaTeXSource(odocstream & os,
191                            std::string const & original_path,
192                            OutputParams const &,
193                            bool output_preamble = true,
194                            bool output_body = true);
195         ///
196         void makeDocBookFile(support::FileName const & filename,
197                              OutputParams const & runparams_in,
198                              bool only_body = false);
199         ///
200         void writeDocBookSource(odocstream & os, std::string const & filename,
201                              OutputParams const & runparams_in,
202                              bool only_body = false);
203         /// returns the main language for the buffer (document)
204         Language const * language() const;
205         /// get l10n translated to the buffers language
206         docstring const B_(std::string const & l10n) const;
207
208         ///
209         int runChktex();
210         /// return true if the main lyx file does not need saving
211         bool isClean() const;
212         ///
213         bool isBakClean() const;
214         ///
215         bool isDepClean(std::string const & name) const;
216
217         /// whether or not disk file has been externally modified
218         bool isExternallyModified(CheckMethod method) const;
219
220         /// save timestamp and checksum of the given file.
221         void saveCheckSum(support::FileName const & file) const;
222
223         /// mark the main lyx file as not needing saving
224         void markClean() const;
225
226         ///
227         void markBakClean() const;
228
229         ///
230         void markDepClean(std::string const & name);
231
232         ///
233         void setUnnamed(bool flag = true);
234
235         ///
236         bool isUnnamed() const;
237
238         /// Mark this buffer as dirty.
239         void markDirty();
240
241         /// Returns the buffer's filename. It is always an absolute path.
242         std::string absFileName() const;
243
244         /// Returns the the path where the buffer lives.
245         /// It is always an absolute path.
246         std::string const & filePath() const;
247
248         /** A transformed version of the file name, adequate for LaTeX.
249             \param no_path optional if \c true then the path is stripped.
250         */
251         std::string latexName(bool no_path = true) const;
252
253         /// Get thee name and type of the log.
254         std::pair<LogType, std::string> logName() const;
255
256         /// Change name of buffer. Updates "read-only" flag.
257         void setFileName(std::string const & newfile);
258
259         /// Name of the document's parent
260         void setParentName(std::string const &);
261
262         /** Get the document's master (or \c this if this is not a
263             child document)
264          */
265         Buffer const * masterBuffer() const;
266         /** Get the document's master (or \c this if this is not a
267             child document)
268          */
269         Buffer * masterBuffer();
270
271         /// Is buffer read-only?
272         bool isReadonly() const;
273
274         /// Set buffer read-only flag
275         void setReadonly(bool flag = true);
276
277         /// returns \c true if the buffer contains a LaTeX document
278         bool isLatex() const;
279         /// returns \c true if the buffer contains a DocBook document
280         bool isDocBook() const;
281         /// returns \c true if the buffer contains a Wed document
282         bool isLiterate() const;
283
284         /** Validate a buffer for LaTeX.
285             This validates the buffer, and returns a struct for use by
286             #makeLaTeX# and others. Its main use is to figure out what
287             commands and packages need to be included in the LaTeX file.
288             It (should) also check that the needed constructs are there
289             (i.e. that the \refs points to coresponding \labels). It
290             should perhaps inset "error" insets to help the user correct
291             obvious mistakes.
292         */
293         void validate(LaTeXFeatures &) const;
294
295         /// Update the cache with all bibfiles in use (including bibfiles
296         /// of loaded child documents).
297         void updateBibfilesCache();
298         /// Return the cache with all bibfiles in use (including bibfiles
299         /// of loaded child documents).
300         std::vector<support::FileName> const & getBibfilesCache() const;
301         ///
302         void getLabelList(std::vector<docstring> &) const;
303
304         ///
305         void changeLanguage(Language const * from, Language const * to);
306
307         ///
308         bool isMultiLingual() const;
309
310         ///
311         BufferParams & params();
312         BufferParams const & params() const;
313
314         /** The list of paragraphs.
315             This is a linked list of paragraph, this list holds the
316             whole contents of the document.
317          */
318         ParagraphList & paragraphs();
319         ParagraphList const & paragraphs() const;
320
321         /// LyX version control object.
322         LyXVC & lyxvc();
323         LyXVC const & lyxvc() const;
324
325         /// Where to put temporary files.
326         std::string const & temppath() const;
327
328         /// Used when typesetting to place errorboxes.
329         TexRow & texrow();
330         TexRow const & texrow() const;
331
332         ///
333         ParIterator par_iterator_begin();
334         ///
335         ParConstIterator par_iterator_begin() const;
336         ///
337         ParIterator par_iterator_end();
338         ///
339         ParConstIterator par_iterator_end() const;
340
341         /** \returns true only when the file is fully loaded.
342          *  Used to prevent the premature generation of previews
343          *  and by the citation inset.
344          */
345         bool isFullyLoaded() const;
346         /// Set by buffer_funcs' newFile.
347         void setFullyLoaded(bool);
348
349         /// Our main text (inside the top InsetText)
350         Text & text() const;
351
352         /// Our top InsetText
353         Inset & inset() const;
354
355         //
356         // Macro handling
357         //
358         ///
359         void buildMacros();
360         ///
361         bool hasMacro(docstring const & name) const;
362         ///
363         MacroData const & getMacro(docstring const & name) const;
364         ///
365         void insertMacro(docstring const & name, MacroData const & data);
366
367         /// Replace the inset contents for insets which InsetCode is equal
368         /// to the passed \p inset_code.
369         void changeRefsIfUnique(docstring const & from, docstring const & to,
370                 InsetCode code);
371
372         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
373         /// including preamble
374         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
375                 bool full_source);
376
377         /// Access to error list
378         ErrorList const & errorList(std::string const & type) const;
379         ErrorList & errorList(std::string const & type);
380
381         //@{
382         TocBackend & tocBackend();
383         TocBackend const & tocBackend() const;
384         //@}
385         
386         //@{
387         EmbeddedFiles & embeddedFiles();
388         EmbeddedFiles const & embeddedFiles() const;
389         //@}
390
391         Undo & undo();
392        
393         /// This function is called when the buffer is changed.
394         void changed() const;
395         /// This function is called when the buffer structure is changed.
396         void structureChanged() const;
397         /// This function is called when some parsing error shows up.
398         void errors(std::string const & err) const;
399         /// This function is called when the buffer busy status change.
400         void setBusy(bool on) const;
401         /// This function is called when the buffer readonly status change.
402         void setReadOnly(bool on) const;
403         /// Update window titles of all users.
404         void updateTitles() const;
405         /// Reset autosave timers for all users.
406         void resetAutosaveTimers() const;
407         ///
408         void message(docstring const & msg) const;
409
410         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
411
412         ///
413         void autoSave() const;
414         ///
415         bool writeAs(std::string const & newname = std::string());
416         ///
417         bool menuWrite();
418         ///
419         void loadChildDocuments() const;
420         /// return the format of the buffer on a string
421         std::string bufferFormat() const;
422
423         ///
424         bool doExport(std::string const & format, bool put_in_tempdir,
425                 std::string & result_file);
426         ///
427         bool doExport(std::string const & format, bool put_in_tempdir);
428         ///
429         bool preview(std::string const & format);
430         ///
431         bool isExportable(std::string const & format) const;
432         ///
433         std::vector<Format const *> exportableFormats(bool only_viewable) const;
434
435 private:
436   /// 
437         bool readFileHelper(support::FileName const & s);
438         ///
439         std::vector<std::string> backends() const;
440         /** Inserts a file into a document
441             \return \c false if method fails.
442         */
443         ReadStatus readFile(Lexer &, support::FileName const & filename,
444                             bool fromString = false);
445
446         /// Use the Pimpl idiom to hide the internals.
447         class Impl;
448         /// The pointer never changes although *pimpl_'s contents may.
449         Impl * const pimpl_;
450
451         /// A cache for the bibfiles (including bibfiles of loaded child
452         /// documents), needed for appropriate update of natbib labels.
453         mutable std::vector<support::FileName> bibfilesCache_;
454
455         frontend::GuiBufferDelegate * gui_;
456 };
457
458
459 } // namespace lyx
460
461 #endif