what's the syntax for telling VI to read/write a source file with soft-tabs and a specified indentation? - emacs

Someplace I saw a snippet of code which told vi to use soft tabs and set the size of a tab. If you put this snippet at the bottom of a source file, then vi would magically use those settings for that file.
What is the syntax and rules for including that snippet in a source file? Can emacs be made to use these settings as well?

You can put this in a comment in your source file:
ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
The comment syntax depends on the type of the source file.
For C/C++/Java, this would be:
// ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
For JSP, this would be:
<%-- ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab: --%>
This works if it is placed at the beginning of the source file, but I'm not sure that this'll work if placed at the end of it too.
This will not work for emacs. There might be a different way of achieving the same for emacs.

Check out :h modeline.
Example:
/* vim: ai set sw=4 ts=4 */
See :h modelines for how many lines into a file Vim will check for modeline info. The default is to check the first 5 lines.

As far as I know, vi didn't have this capability. You're likely thinking of the modeline feature of Vim. There is similar functionality in emacs, where you can put local variables in the file.
Note that, at least in Vim, modelines have had a history of vulnerabilities. This is primarily due to problematic options being specifically blacklisted instead of only allowing a certain subset of variables to be set in modelines. I'd suggest using a plugin like securemodelines.

Put this in your C++ source file:
// vim: set ft=cpp
The modeline feature looks for the string "vim:" and then executes what follows. Note: this could open up potential exploits if you don't trust the files you are opening, so think twice before enabling this feature.

Okay, first of all, in real vi you do this in the .exrc file.
Second, use
set autoindent tabstop=8 shiftwidth=4
because otherwise vi will insert tabs it thinks are only 4 characters wide. The resulting text file will not look like it makes sense in any other editor.

Related

Highlighting lines in emacs

I am using an IM which does not support viewing previous chat history nor can I change my IM. So I have to copy the chat into a text file everytime.
I am using Emacs.Is there some way by which I can highlight the lines which contain the participant names as below?
===> **[Vivek Kumar]**
Hi, how are you doing!
===> **[Mr X Y Z]**
fine
===> **[Vivek Kumar]**
sdfksd;fks;
EDIT 1:
Earlier when I'd access to gvim, I would use the highlight.vim plugin.
Emacs supports highlighting of lines or phrases. You can use one of highlight-lines-matching-regexp, highlight-phrase, or highlight-regexp. I'm sure there are several others too.
To try this, paste your text into the editor, press ESC-x (or Alt-x might work too) to enter the "mini-buffer" at the bottom of the editor window, and enter one of the above commands.
For example, I tried:
highlight-lines-matching-regexp and entered the regexp "\[.*\]" and made it match the names in your example. Here's a screenshot:
You can tweak this expression to fit your needs. Some links to regular expressions in emacs:
http://www.emacswiki.org/emacs/RegularExpression
This question on SO: Good tutorial + reference for Emacs search and replace?
Of course you could also use highlight-phrase and just highlight a simple string of text (instead of messing with regexes).
Here's one where I ran highlight-phrase and entered the two separate names and gave them different colors (hi-yellow and hi-red):
Finally you can then run unhighlight-regexp to clear out the highlighting.

how to freely format comments in cc-mode

I'm quite new to cc-mode and I'd like to configure it to allow me to freely format and use tabs in multiline comments. This is important to me because I want to use cog.py in my source file and need to be able to format the python source in the comment correctly. I'd be ok with comments not beeing autoindented at all, however I'd like to keep auto indenting the rest of the source code.
Example:
...
/*
[[[cog
import cog
for x in ['a','b','c']:
>cog.outl(x)
]]]
*/
...
In the line marked with > I'd like to press TAB to indent the line. cc-mode simply does nothing at all if i do so. I could use spaces there (which is inconvenient) but every (semi-)automatic re-indentation of this block would cause the spaces to vanish and therefore the python code to be incorrectly indented (which is what happens if i happen to press tab somewhere on this line after indenting it with spaces).
I tried to start emacs without my .init to be sure this is default behavior and not modified by my configuration so far. I've done google searches and read the documentation of the cc-mode variables / functions I stumbled upon (cc-mode online docs) while searching for a solution (i.e. c-indent-comments-syntactically-p, c-indent-command, c-tab-always-indent,...) but none of these seemed to solve my question.
EDIT1:
Thanks to abo-abo's idea of a "multi-major-mode" setup i've stumbled upon mmm-mode and have set up automatic switching to python mode for a cog section, which fixes most of my problems.
The only remaining problem is reindenting the whole file or a region containing a cog section. Can I somehow tell cc-mode to not change anything in comments while reindenting the file? mmm-mode + that would be a perfect solution for me.
You can use M-i to force a tab indent on the lines that you want, so you can use it to indent your comments.
You can also change your comments to use // instead. Just select your python code snippet, and do M-x comment-region:
// def foo(x):
// print 'hi'
Then the autoindent won't mess up your indentation.

Emacs Gnus Faces (Fonts)

The slrn newsreader has an attractive interface with different colours for the author, subject and date columns when browsing list of articles in a newsgroup. I am looking for the Emacs font/face variables for these fields in gnus, but have not been able to find them. The gnus manual for faces does not list the available faces and none of the faces list in Emacs (M-x customize-face gnus-... looks relevant. I am using gnus 5.13 in Emacs 23.2.1.
(This question is not related to displaying "faces" (icons/avatars) in Emacs or gnus.)
Solved: See my answer below.
I think they're scattered a bit in the gnus codebase. The faces used in the article buffer are probably in gnus-art.el, etc.
It sounds like your biggest problem is that there are specific faces that you can't find the symbol for. You can always do M-x describe-face to see what is under the cursor to solve that problem.
Also, (face-list) returns a list of all defined faces. You could scan that list looking for things that look like likely candidates for the particular faces you're interested in.
The format string for various elements in gnus can be customized by modifying the appropriate variable. The variable for the summary line is gnus-summary-format-line. I am not using the default value for this variable, but instead am using the value %U%R%z %(%&user-date; %-15,15f %* %B%s%)\n.
As described here, a new face can be applied to any (sub)section of a format line by bracketing the section with %1{ and %}, where the 1 in this example corresponds to gnus-face-1. gnus-face-1 in my installation defaults to "italics", so adding the following to my ~/.emacs file results in the author in the summary line appearing in italics:
(setq gnus-summary-line-format "%U%R%z %(%&user-date; %1{%-15,15f%} %* %B%s%)\n")
I go with M-x list-faces-display (which opens a new buffer with all the currently defined face variables fontified to the color that they're set to, in alphabetic order) when I want to see what faces I need to change to get a mode working.
Then I setq them, using either the format from color-theme or from the new emacs built-in theme format, depending on which version of emacs I'm in.

lazy loading of only the first N lines in emacs org-mode

Is there a way to tell org-mode to load only the first N lines of a long text file? I would like to keep the whole file open to be able to search through it, but have org-mode display on the first N lines of my file, which is where I edit new content.
If you have a structured outline in org-mode, you can set the global file visibility with the #+STARTUP markup, or the visibility of any heading with the VISIBILITY property, see Visibility Cycling for details. The benefit of using the built-in org-mode properties is that it's easy to have a file open up in exactly the state you want.
I have my journal file set up to accomplish something similar what I think you're asking for using these org-mode properties. The "Today" section is opened so I can see everything, but older archives are collapsed.
I'm not sure the title really fits the description?
I think you just want use buffer narrowing, which lets you hide everything outside of the specified region for as long as necessary.
You can manually narrow the buffer by marking the region and typing C-xnn
Widen the display back to the full buffer with C-xnw
I guess you could use an eval Local Variable to automate this to a pre-defined region, if you really wanted to.
There's also narrow-to-defun (C-xnd) and narrow-to-page (C-xnp). If you throw a page break into your org file (C-qC-l), the latter might prove handy.

How do you display code snippets in MS Word preserving format and syntax highlighting?

Does anyone know a way to display code in Microsoft Word documents that preserves coloring and formatting? Preferably, the method would also be unobtrusive and easy to update.
I have tried to include code as regular text which looks awful and gets in the way when editing regular text. I have also tried inserting objects, a WordPad document and Text Box, into the document then putting the code inside those objects. The code looks much better and is easier to avoid while editing the rest of the text. However, these objects can only span one page which makes editing a nightmare when several pages of code need to be added.
Lastly, I know that there are much better editors/formats that have no problem handling this but I am stuck working with MS word.
Here is the best way, for me, to add code inside word:
Go to Insert tab, Text section, click Object button (it's on the right)
Choose OpenDocument Text which will open a new embedded word document
Copy and paste your code from Visual Studio / Eclipse inside this embedded word page
Save and close
Advantages
The result looks very nice. Here are the advantages of this method:
The code keeps its original layout and colors
The code is separated from the rest of the document, as if it was a picture or a chart
Spelling errors won't be highlighted in the code (this is cool !)
And it takes only few seconds.
Download and install Notepad++ and do the following:
Paste your code in the window;
Select the programming language from the language menu;
Select the text to copy;
Right click and select Plugin commands -> Copy Text with Syntax Highlighting;
Paste it into MS Word and you are good to go!
Update 29/06/2013:
Notepad++ has a plugin called "NppExport" (comes pre-installed) that allows you to copy to RTF, HTML and ALL. It permits dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).
I use Copy all formats to clipboard and "paste as HTML" in MS word.
After reading a lot of related answers, I came across my own solution, which for me is the most suitable one.
Result looks like this:
As you can see, it is the same syntax highlighting like on Stack Overflow which is quite awesome.
Steps to reproduce:
on Stack Overflow
Goto Ask Question (preferably with Chrome)
Paste Code and add a language tag (e.g. Java) to get syntax hightlighting
Copy code from preview
in Word
Insert > Table > 1x1
Paste code (you may need to use Paste Special... > Formatted Text (RTF) from the Edit menu to not lose the syntax hilighting)
Table Design > Borders > No Border
Select code > Edit > Find > Replace
Search Document ^p (Paragraph Mark)
Replace With ^l (Manual Line Break)
(This is required to remove the gaps between some lines)
Select code again > Review > Language > check "Do not check spelling or grammar"
Finally add a caption using References > Insert Caption > New Label > name it "Listing" or sth
Sample code thanks to this guy
There is a nice Online Tool for that : https://www.troye.io/planetb/
Just copy the generated code and paste it into your word editing software. So far I've tried it on MS Word and WPS Writer, works really well.
Doesn't play nice with Firefox but works just fine on Chrome (and IE too, but who wants to use that).
One of the main benefits is that, unlike the Code Format Add-In for Word, it does NOT mess with your code, and respects various languages' syntax.
I tried many other options offered in other answers but I found this one to be the most efficient (quick and really effective).
There is also another online tool quoted in another answer (markup.su) but I find the planetB output more elegant (although less versatile).
Input :
Output :
I type my code in Visual Studio, and then copy-paste into word. it preserves the colors.
When I've done this, I've made extensive use of styles. It helps a lot.
What I do is create a paragraph style (perhaps called "Code Example" or something like that) which uses a monospaced font, carefully chosen tabs, a very light grey background, a thin black border above and below (that helps visibility a lot) and with spelling turned off. I also make sure that inter-line and inter-paragraph spacing are set right. I then create additional character styles on top (e.g., "Comment", "String", "Keyword", "Function Name Decl", "Variable Name Decl") which I layer on top; those set the color and whether the text is bold/italic. It's then pretty simple to go through and mark up a pasted example as being code and have it come out looking really good, and this is works well for short snippets. Long chunks of code probably should not normally be in something that's going to go on a dead tree. :-)
An advantage of doing it this way is that it is easy to adapt to whatever code you're doing; you don't have to rely on some IDE to figure out whatever is going on for you. (The main problem? Printed pages typically aren't as wide as editor windows so wrapping will suck...)
Maybe this is overly simple, but have you tried pasting in your code and setting the font on it to Courier New?
Try defining a style called 'code' and make it use a small fixed width font, it should look better then.
Use CTRL+SPACEBAR to reset style.
If you are using Sublime Text, you can copy the code from Sublime to MS Word preserving the syntax highlighting.
Install the package called SublimeHighlight.
In Sublime, using your cursor, select the code you want to copy, right click it, select 'copy as rtf', and paste into MS Word.
I'm using Easy Code Formatter. It's also an Office add-in. It allows you to select the coding style / and has a quick formatting button. Pretty neat.
In case you're like me and are too lazy or in a hurry and don't want to download additional software, you can use http://markup.su/highlighter/. It's very straight forward and supports several highlight themes and many programming languages. In my case I was using Visual Studio Code, which doesn't allow copying with format due to CSS involved in styling (as reported here).
Copy the text from the Preview box and then in Word go to Insert -> Textbox, paste the Preview from the website, highlight all the text, and then disable spell checking for that textbox.
This is what the code looks like finally.
The best way I found is by using the table.
Create a table with 1x1. Then copy the code and paste it.
If you're using the desktop app then it will inherit the code editor theme color and paste it accordingly, else you can change the table style to any color.
UPDATE ------------------
From Word 2021, you can directly paste the code and it will preserve the formatting. No need to create the table.
Thank you #RdC1965 for mentioning this.
This is a bit indirect, but it works very nicely. Get LiveWriter and install this plugin:
http://lvildosola.blogspot.com/2007/02/code-snippet-plugin-for-windows-live.html
Insert your code using the plugin into a blog post. Select all and copy it to Word.
It looks great and can include line numbers. It also spans pages decently.
HTH
Colby Africa
Vim has a nifty feature that converts code to HTML format preserving syntax highlighting, font style, background color and even line numbers. Run :TOhtml and vim creates a new buffer containing html markup.
Next, open this html file in a web browser and copy/paste whatever it rendered to Word. Vim tips wiki has more information.
In my experience copy-paste from eclipse and Notepad++ works directly with word.
For some reason I had a problem with a file that didn't preserve coloring. I made a new .java file, copy-paste code to that, then copy-paste to word and it worked...
As the other guys said, create a new paragraph style. What I do is use mono-spaced font like courier new, small size close to 8px for fonts, single spaced with no space between paragraphs, make tab stops small (0.5cm,1cm,..,5cm), put a simple line border around the text and disable grammar checks. That way i achieved the line braking of eclipse so I don't have to do anything more.
Hope I helped ;)
This is the simplest approach I follow. Consider I want to paste java code.
I paste the code here so that spaces, tabs and flower brackets are neatly formated http://www.tutorialspoint.com/online_java_formatter.htm
Then I paste the code got from step 1 here so that the colors, fonts are added to the code http://markup.su/highlighter/
Then paste the preview code got from step 2 to the MS word. Finally it will look like this
You can use VS code to keep code format and highlighting. Directly copy and paste code from VS.
you can simply use this Add-in on any office program.
Go to insert tab, then Get Add-ins, and search for Easy Syntax Highlighter
It supports
185 languages and 89 themes.
Automatic language detection.
Multi-language code highlighting.
Use a monospaced font like Lucida Console, which comes with Windows. If you cut/paste from Visual Studio or something that supports syntax highlighting, you can often preserve the colour scheme of the syntax highlighter.
Answer for people trying to resolve this issue in 2019:
Most answers to this question are outdated by now. I wish there was a way to reinspect old questions and answers every now and then!
The method I found for this question that works with Office 365 and its associated programs can be found here.
I'm using Word 2010 and I like copying and paste from a github gist. Just remember to keep source formatting!
I then change the font to DejaVu Sans Mono.
You can opt to copy with or without the numbering.
Copying into Eclipse and paste it in Word is also another option.
You can also use SciTE to paste code if you don't want to install heavy IDEs and then download plugins for all the code you're making. Simply choose your language from the language menu, type your code, high-light code, select Edit->Copy as RTF, paste into Word with formatting (default paste).
SciTE supports the following languages but probably has support for others: Abaqus*, Ada, ANS.1 MIB definition files*, APDL, Assembler (NASM, MASM), Asymptote*, AutoIt*, Avenue*, Batch files (MS-DOS), Baan*, Bash*, BlitzBasic*, Bullant*, C/C++/C#, Clarion, cmake*, conf (Apache), CSound, CSS*, D, diff files*, E-Script*, Eiffel*, Erlang*, Flagship (Clipper / XBase), Flash (ActionScript), Fortran*, Forth*, GAP*, Gettext, Haskell, HTML*, HTML with embedded JavaScript, VBScript, PHP and ASP*, Gui4Cli*, IDL - both MSIDL and XPIDL*, INI, properties* and similar, InnoSetup*, Java*, JavaScript*, LISP*, LOT*, Lout*, Lua*, Make, Matlab*, Metapost*, MMIXAL, MSSQL, nnCron, NSIS*, Objective Caml*, Opal, Octave*, Pascal/Delphi*, Perl, most of it except for some ambiguous cases*, PL/M*, Progress*, PostScript*, POV-Ray*, PowerBasic*, PowerShell*, PureBasic*, Python*, R*, Rebol*, Ruby*, Scheme*, scriptol*, Specman E*, Spice, Smalltalk, SQL and PLSQL, TADS3*, TeX and LaTeX, Tcl/Tk*, VB and VBScript*, Verilog*, VHDL*, XML*, YAML*.
If you are using Intellij IDEA, just copy the code from the IDE and paste it in the word document.
A web site for coloration with lots of languages.
http://hilite.me/
You can host one yourself since it is open source. The code is on github.
There really isn't a clean way to do it, and it could still look fishy based on your exact style settings.
What you could try to do is to first run a code-to-HTML conversion (there are many programs that do that), and then try to open up the HTML file with word, that might hopefully provide you with the formatted and pretty code, and then copy and paste it into your document.
I was also looking for it and ended up creating something for my code display.
Here's a good way:
Create a rectangular form and place your text inside.
Change the font to Consolas and size ~10.
Change the text font to gray near-black (gray 25%, darker 75%)
Use darker colors to highlight your text if needed and choose one to be the contour.
I have created an easier method using tables, as they are easier to create, manage, and more consistent (with the possibility to save the table's style inside the document itself), but I couldn't find a better way for code colouring scheme, sorry for that.
Steps:
Create a 3x3 table.
Select the table, and make its borders invisible ("No Borders" option), and activate "View Gridlines" option.
Make the adjustments to cells' spacing and columns' widths to get the desired aspect. (You will have to get in "Table Properties" for fine tuning).
Create a "Paragraph Style" with the name of "Code" just for your code snippets (as mentioned in https://stackoverflow.com/a/25092977/8533804)
Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style, but this you will add a numbering line in its definition (this will automate line numbering).
Apply "Code_numberline" to the first column, and "Code" to the 3 column.
Add a fill in the middle column.
Save that table style and enjoy!
The best presentation for code in documents is in a fixed-width font (as it should appear in an IDE), with either a faint, shaded background or a light border to distinguish the block from other text.
If its Java source code copy it to Visual Studio and then copy it back to Word.