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