Different Styles in PlainView - Syntax Highlighting?

Hi,
I've managed to extend PlainView and looking at old JEdit code I have the syntax highlighting working for the most part. However, at certain times while typing the cursor starts to get way ahead of the text it's typing. And as I backspace on the line the cursor eventually gets closer to the character the closer it gets to the start of the line.
I'm overridding the "drawUnselectedText()" method in PlainView to do the coloring.
Here's the code, you can see the call to SyntaxUtilities.paintSyntaxLine() which is JEdit's class to do the drawing.
         * Renders the given range in the model as normal unselected text. This
         * is implemented to paint colors based upon the token-to-color
         * translations. To reduce the number of calls to the Graphics object,
         * text is batched up until a color change is detected or the entire
         * requested range has been reached.
         * @param g
         *            the graphics context
         * @param x
         *            the starting X coordinate
         * @param y
         *            the starting Y coordinate
         * @param p0
         *            the beginning position in the model
         * @param p1
         *            the ending position in the model
         * @returns the location of the end of the range
         * @exception BadLocationException
         *                if the range is invalid
        protected int drawUnselectedText(Graphics g, int x, int y, int p0, int p1) throws BadLocationException {
            System.out.println("p0: " + p0 + " p1: " + p1 + " x: " + x + " y: " + y);
            // Get the start of the element
            int lineIndex = doc.getDefaultRootElement().getElementIndex(p0);
            // Get the element for the line
            Element elem = doc.getDefaultRootElement().getElement(lineIndex);
            System.out.println("lineIndex: " + lineIndex + " elemStartIDX: " + elem.getStartOffset() + " elemEndIDX: " + elem.getEndOffset());
            // Get the line text
            doc.getText(p0, p1 - p0, currentLineText);
            // If highlighting, mark the tokens
            if (marker != null) {
                Token t = marker.markTokens(currentLineText, lineIndex);
                x = SyntaxUtilities.paintSyntaxLine(currentLineText, t, styles, this, g, x, y, p0, p1);
                System.out.println("Painted line at: " + x);
            } else {
                // No highlighting requested, draw normal text
                Font defaultFont = g.getFont();
                Color defaultColor = styles[0].getColor(); // Default color of text
                g.setFont(defaultFont);
                g.setColor(defaultColor);
                x = Utilities.drawTabbedText(currentLineText, x, y, g, this, p0);
            // Set the last line processed
            lastLine  = lineIndex;
            return x;
Here is the code from the paintSyntaxLine() method:
     * Paints the specified line onto the graphics context. Note that this
     * method munges the offset and count values of the segment.
     * @param line
     *            The line segment
     * @param tokens
     *            The token list for the line
     * @param styles
     *            The syntax style list
     * @param expander
     *            The tab expander used to determine tab stops. May be null
     * @param gfx
     *            The graphics context
     * @param x
     *            The x co-ordinate
     * @param y
     *            The y co-ordinate
     * @return The x co-ordinate, plus the width of the painted string
    public static int paintSyntaxLine(Segment line, Token tokens, SyntaxStyle[] styles, TabExpander expander, Graphics gfx, int x, int y, int p0, int p1) {
        Font defaultFont = gfx.getFont();
        Color defaultColor = Color.black;
        FontMetrics fm = gfx.getFontMetrics(defaultFont);
        int offset = 0;
        while (tokens != null && tokens.id != Token.END) {
            int length = tokens.length;
            if (tokens.id == Token.NULL) {
                if (!defaultColor.equals(gfx.getColor()))
                    gfx.setColor(defaultColor);
                if (!defaultFont.equals(gfx.getFont()))
                    gfx.setFont(defaultFont);
            } else {
                styles[tokens.id].setGraphicsFlags(gfx, defaultFont);
//                fm = gfx.getFontMetrics();//[tokens.id].getStyledFont(defaultFont);
//                FontMetrics dfm = Toolkit.getDefaultToolkit().getFontMetrics(defaultFont);
//                System.out.println("Font Info: CharWidth[" + fm.charWidth(line.array[p1])+"], Max Advance[" + fm.getMaxAdvance()+"]");
//                System.out.println("Default Font Info: CharWidth[" + dfm.charWidth(line.array[p1])+"], DMax Advance[" + dfm.getMaxAdvance()+"]");
////                x = fm.charsWidth(line.array, p0, length);
            line.count = length;
            x = Utilities.drawTabbedText(line, x, y, gfx, expander, p0);
            line.offset += length;
            offset += length;
            tokens = tokens.next;
        return x;
I'm not sure what the problem is..i thought it might be an issue with the View and drawing multiple font styles. Since plain view only deals with a single font color and size. I tried using LabelView but that seems to need a StyledDocument and I had problems when I tried to use DefaultStyledDocument for my syntaxdocument. I was getting strange offset issues when using the Segment class.
Here's what I posted: http://forum.java.sun.com/thread.jspa?threadID=780801
I am using PlainDocument because that seemed to be what everyone was using for a syntax editor..since the structure of the document in a Plain Document is less complex.
I orginally started out using the setCharacterAttributes() method on the DefaultStyledDocument and letting the views draw the text. That all seemed to work except for the "segment offset" issue. And I wasn't sure where the best spot to get the document to redraw subsequent lines in the case of changing a multiline comment, etc.
So, everything I read about others attempts for syntax highlighters seems to use either StyledEditorKit with a fixed language set with custom parsing and using the setCharacterAttributes method. Or they use the plaindocument approach with a custom view..(which no one seems to share the source) or the project just simply uses the JEditTextArea directly (which we can't do in our product).
We don't need multiple fonts per-line.. The document will always use one font face (Arial, Helvetica, etc) but may use different styles per word (bold, italic, etc).
I thought I'd need to use FontMetrics to get the size of the font and such. But there didn't seem to be a difference in measurements based on the style of the font. (i.,e A bold font has the same charWidth('m') size as a regular style.
At least that's what my test program showed..
The other thing I noticed is that when the document is successfully colored and I use the mouse to select a region of text, the style of the text reverts back to normal. I'm sure that's because I only override the drawUnselectedText() method.
Any ideas? Is there anyone who has successfully done this?
Thanks,
- Tim

I just tried using a proportional font in my editor, and now I'm seeing your runaway-caret problem. Specifically, the caret remains in sync with the text as long as no bold characters are encountered, but it gets noticeably farther out of whack with each bold character it passes. I suspect that, when you measured the charWidth, your FontMetrics object wasn't really based on a bold font, because bold versions of proportional fonts are larger. And of course, the model/view conversion methods assume that the same style of the same font is used throughout the document. I've never had to deal with that problem, since I've always used monospaced fonts by preference, and bold versions of monospaced fonts really are the same size as the non-bold versions. I suggest you do the same, because getting this to work with proportional fonts look like a major hassle.

Similar Messages

  • [SOLVED] VIM: different syntax highlighting for new vs existing file

    I've had this minor nagging issue for a while that I've been trying to figure out, but I just don't know where to look.
    It is most obvious with LaTeX files (*.tex).  When I create a new file with "vim file.tex" it is recognized as a latex file and I get syntax highlighting, but it seems odd, or off.  When I close then reopen the same file, it gets "propper" syntax highlighting.
    I gather that this must be because of the two different mechanisms for matching the syntax type: filename versus content.  When the file is new, vim only uses the extension.  Once there is a latex comand (e.g., "\documentclass{article}") it recognizes it as something else and the highlighting style is different.
    It turns out just by actually elaborating exactly what the problem was, I was able to find the solution.  I looked for how vim recognizes the files, and found two relevant lines in /usr/share/vim/vim73/filetype.vim on lines 2093 and 2094.  Apparently the .tex filetype is not the same as .latex and others.  I changed it so it was, and I got the desired behavior.
    I thought about just not posting this - but it may be useful for others.

    You're right about it being overridden.  This change should be able to be placed in ~/.vimrc though.
    Well  that was foolish - I should have read the comments right below in that file.  It says exactly how to set it in vimrc.  I've now added the following to my ~/.vimrc and this is completely solved without modifying the /usr/... file.
    let g:tex_flavor = "tex"
    Last edited by Trilby (2013-03-29 16:11:26)

  • Syntax Highlighting w/ Swing Text Package

    I have a question for you that I hope ever so much that you could answer just in the most abstract sense, I will figure out the code from what you have said hopefully. Any relavent parts that you think I should know, please point out.
    My question is, I'm trying to implement Syntax Highlighting for a code editor in Java (yes I know, like everyone else. It would REALLY be helpful if you did an updated Demo of a SyntaxEditor for JDK 1.4 BTW) anyway, I have already implemented Syntax Highlighting by overriding the PlainView and changing its drawLine method to parse the line, find the key words then draw them accordingly. However I cannot get over the sinking feeling that there is a better way to do this in JDK 1.4, I'm not worried about backward compatability. I'm only interested in the "sexiest" way to do this with Java. I started looking into the GlyphView, and that seems more of what I want, it has more control over the text elements and strong drawing abilities, I also noticed the GlyphPainter1 and GlyphPainter2, I tried to extend GlyphPainter2 and use it with my extended GlyphView and just change its paint method to parse the lines, but the class complains about not being public, even though in the source its class definition is "public class GlyphPainer2 extends GlyphView.GlyphPainter" which confused me.
    But at any rate, my basic question is how would YOU, implement Syntax Highlighting (code coloring) if you could do it from scratch with all the facilities of the 1.4 JDK. ALso, should I look into the Java2D API or is this over kill for what I'm doing? I just need a basic code color'er, nothing fancy. But I need the fonts and styles to be able to change, that's all. And international support would be nice.
    The type of answer I'm hoping for is something like "Create a new editor kit and then extend the GlyphView class and override its XYZ method to do your line parsing and then override the ABC method to do the actual painting of the line, this is the best way to do this in java"
    Best wishes,
    -rsk123

    I am searching for text highlighting code in java during 7 days.
    And I also agree with Mr. rsk123 's thought.
    I want to make editor to highlight code using java's general text package.
    But I can't find good source or class to satisfy me.
    Some code run well but it's not use the original java text package.
    Some code was made by using java text package but have a bug and not run pefectly.
    Now, I must choice a code for text highlighting.
    But until now I can't find a free code or comecial code for it.
    Anyway, I summarize my suffing result until now.
    ** I have stuied,
    . About java's text package in Swing Connection site.
    It's useful a little to understand the text package structure.
    (http://java.sun.com/products/jfc/tsc/articles/index.html)
    . How to make own EditorKit in 'Java Swing' book chapter 24.
    I think it's good. But difficult to read.
    (published by O'REILLY. Robert Eckstein)
    ** I have found program and have tested.
    1) JEdit (http://www.jedit.org)
    2) Jext(http://www.jext.org)
    3) Sun's sample using the JavaEditorKit
    (http://java.sun.com/products/jfc/tsc/articles/text/editor_kit/index.html)
    4) Ostermiller's Syntax editor (http://ostermiller.org/syntax/editor.html)
    5) j (http://armedbear-j.sourceforge.net/)
    6) je 1.66 (http://mathsrv.ku-eichstaett.de/MGF/homes/grothmann/je/)
    *** Detail descriptions of the test
    1. May be run well but not use java text package.
    ==> JEdit (http://www.jedit.org), Jext(http://www.jext.org)
    - I executed JEdit and Jext program. it works very well.
    I think It's greate programs.
    - The editor class for these programs are
    org.gjt.sp.jedit.textarea.JEditTextArea class.
    The JEditTextArea class extends JComponent, not java text component.
    - JEditTextArea class started from 'jedit syntax package project'.
    You can download the syntax package if you only use syntax highlighting
    from http://syntax.jedit.org/ .
    - JEdit and Jext use for editor 'jedit syntax package' but have upgrade that
    package their own effort(may be)
    - For me, It's an only product run well without error.
    But unfortunately it's not use java text component.
    So I hesitane to use it.
    Because I should make almost code to support general editor function which
    supported in JTextComponent.
    2. Provided by Sun's developer site.
    ==> JavaEditorKit (http://java.sun.com/products/jfc/tsc/articles/text/editor_kit/index.html)
    - It's made using JEditorPane. Great!!
    And have a good architecture. (I think)
    - But It use Scanner class which located in tools.jar package and
    have a bug which not supporting well comment syntax /* */.
    (Refer to http://developer.java.sun.com/developer/bugParade/bugs/4323090.html)
    Futhermore it display terrible exception message when typed "/*" string
    in the end position of java file. (I tested it)
    - I heard in the forum, someone made the own scanner class.
    (http://forum.java.sun.com/thread.jsp?thread=120564&forum=57&message=316083)
    He said,(he = rofshi)
    I wrote for my purposes a scanner based on the StreamTokenizer
    cl*** and set a corresponding object in the JavaView cl*** of
    the JavaKitTest.
    Then I placed the method of my Scanner cl*** that parses the
    given string and paints tokens in the method drawUnselected
    Text (instead of previous code).
    Of course, I erased all of the previous code related to the
    java Scanner.
    - For me, I like this style code and want to use it.
    But Scanner class have some bug and I can't cure that bug. Terrible...
    3. using JTextPane
    ==> http://ostermiller.org/syntax/editor.html
    - At first it's too slow.
    My computer is PentiumIII 350MHz Ram:256M Windows2000Por
    But when I press pgDown key quickly the display couldn't follow it.
    - And may be not support unicode.
    When I typed international code, exceptions displayed.
    (too much exceptios. may be caused repeating by thread.)
    (ArrayIndexOutOfBoundsException in JavaLexer.java 1022 ?)
    - For me, supporting international code is essential.
    So I can't use it.
    4. Do work well. But it use not understandable code for me.
    (not use general java text package)
    1)http://armedbear-j.sourceforge.net/
    2)http://www.rene-grothmann.de
    *** Finally, I have plan to make my own code using Mr rsk123's idea.
    (using GlyphView in jdk1.3 or jdk1.4)
    *** If you have a good information for text highliting of free code or
    comecial code pleas notify me.
    My address is [email protected]

  • How to enable syntax highlighting for jspf files on Dreamweaver CS5.5 on Mac

    I ran into an issue where I couldn't get the color coding (color coding style) for java server pages fragments (.jspf) files to show syntax highliting.
    I followed the adobe instructions on Changing and adding file extensions recognized by Dreamweaver without any luck.
    Here is the solution that worked for me:
    On a Mac:
    1. Edit the /Users/YOUR USER/Library/Application Support/Adobe/Dreamweaver CS5.5/en_US/Configuration/DocumentTypes/MMDocumetTypes.xml
    Note: the Adobe instructions tell you to edit /Applications/Adobe Dreamweaver CS5.5/Configuration/DocumentTypes/MMDocumetTypes.xml (Editing this file didn't do anything for me, so you need to change the file above instead)
    Find,
    <documenttype id="JSP" servermodel="JSP" internaltype="Dynamic" winfileextension="jsp,jst" macfileextension="jsp,jst" file="Default.jsp" writebyteordermark="false" mimetype="text/html">
    Replace with,
    <documenttype id="JSP" servermodel="JSP" internaltype="Dynamic" winfileextension="jsp,jst,jspf" macfileextension="jsp,jst,jspf" file="Default.jsp" writebyteordermark="false" mimetype="text/html">
    2. Edit the /Users/YOUR USER/Library/Application Support/Adobe/Dreamweaver CS5.5/en_US/Configuration/Extensions.txt
    In the All: section on top add the jspf extention right after jsp in my example it looked like this
    HTM,HTML,SHTM,SHTML,HTA,HTC,XHTML,STM,SSI,JS,JSON,AS,ASC,ASR,XML,XSL,XSD,DTD,XSLT,RSS,RDF, LBI,DWT,ASP,ASA,ASPX,ASCX,ASMX,CONFIG,CS,CSS,CFM,CFML,CFC,TLD,TXT,PHP,PHP3,PHP4,PHP5,PHP-D IST,PHTML,JSP,WML,TPL,LASSO,JSF,VB,VBS,VTM,VTML,INC,SQL,JAVA,EDML,MASTER,INFO,INSTALL,THEME,CONFIG,MODU LE,PROFILE,ENGINE,SVG:All
    and I added the jspf and it looks like this now,
    HTM,HTML,SHTM,SHTML,HTA,HTC,XHTML,STM,SSI,JS,JSON,AS,ASC,ASR,XML,XSL,XSD,DTD,XSLT,RSS,RDF, LBI,DWT,ASP,ASA,ASPX,ASCX,ASMX,CONFIG,CS,CSS,CFM,CFML,CFC,TLD,TXT,PHP,PHP3,PHP4,PHP5,PHP-D IST,PHTML,JSP,JSPF,WML,TPL,LASSO,JSF,VB,VBS,VTM,VTML,INC,SQL,JAVA,EDML,MASTER,INFO,INSTALL,THEME,CONFIG,MODU LE,PROFILE,ENGINE,SVG:All
    That's it, Quit Dreamweaver and open it up again. Open the .jspf file and see the color coding (syntax highlighting)
    Hope this helps you and seves you time figuring it out. If this helped, do a good thing, next time you figure something out, tell others about it to save their time too, like I did. Enjoy.

    TheGrandNabib wrote:
    I don't seem to have a user Library folder, my only Library folder is on the same level as my Users folder.
    From Locating your personal configuration folder in the Dreamweaver FAQ:
    In Mac OS X (Lion and Mountain Lion), open Finder and press Shift-Cmd-Go. Type ~/Library/Application Support in the dialog box, and click Go. You should then be able to find the configuration folder.

  • Help required in syntax highlighting in xml using tool Syntax

    hi
    i am using Syntax tool for syntax highlighting of xml in JTextpane. I use complex html style and i want to change the colors of the displayed xml in the tool under complex html like the internet explorer displays in case of xml i want to make my xml like that..

    Hi,
    use it like this if Fname equals constnat[space] then pass the Constant[space] to Fname else value of Fname as under
    ................................Constant[]------>
    FNAME.............................................Then
    >Equals....................................IF -
    >FNAME
    Constant[].........................................ELSE
    .......................................FNAME---->   
    Constant[]    = Constant [ Space ]
    Sachin

  • Custom Styles in TextEdit - Background Highlighting

    Hi, I defined a custom/'favorite' style for use in TextEdit which applies yellow background highlighting to selected text. (The style was added to the GlobalPreferences.plist file, as I'm on Snow Leopard). The issue is that when I highlight text and apply this style, it overrides any prior formatting like bold, italic, or underline, and reverts the selection to plain text when applying the background highlighting.
    I understand this is mechanically correct, because my user-defined Highlight style induces [plain text + yellow background color]. My question is this: is there any way to modify my defined style to preserve the original formatting of the text, adding only the background color without modifying the pre-existing text attributes? Basically I would like my bold, italic, underline, strikethroughs, font size, etc. to be preserved when applying a background color to selected text.
    For reference, I defined the style by electing to 'add to favorite styles' a selection from one of the similarly pre-formatted rich text files that's available, and did NOT include the font or the ruler as part of the style. I understand that I could create separate favorite styles for highlight+bold, highlight+italic, highlight+underline, highlight+strikethrough, highlight+[each font size], and all combinations thereof, but applying each different style to each subsection of text would be as cumbersome as reformatting each subsection as +bold, +italics, etc. after the highlight it applied and text style is reverted to default.
    I have extracted the NSFavoriteStyles section from the ~/Library/Preferences/GlobalPreferences.plist file and located the style I defined, it appears like this:
    Highlighter =     {
            NSBackgroundColor = <62706c69 73743030 d4010203 04050615 16582476 65727369 6f6e5824 6f626a65 63747359 24617263 68697665 72542474 6f701200 0186a0a3 07080f55 246e756c 6cd3090a 0b0c0d0e 5624636c 6173735c 4e53436f 6c6f7253 70616365 554e5352 47428002 10014831 20312030 2e3200d2 10111213 5a24636c 6173736e 616d6558 24636c61 73736573 574e5343 6f6c6f72 a2121458 4e534f62 6a656374 5f100f4e 534b6579 65644172 63686976 6572d117 1854726f 6f748001 08111a23 2d32373b 41484f5c 6264666f 747f8890 939caeb1 b6000000 00000001 01000000 00000000 19000000 00000000 00000000 00000000 b8>;
    What would I need to add to this string to retain existing text formatting when applying the style? It should be possible, as applying the 'Underline' style does not override an existing 'Bold' style, for example, but I don't see any commands in those styles that supplement the information that appears in my defined 'Highlighter' style.
    I also understand this may be pre-Lion specific, as I've heard the TextEdit program is now sandboxed in such a way as to prevent the definition of new styles. I'll have to try on my Mountain Lion machine when I have a chance. I appreciate any help, thanks!

    Hello
    It's been a while and I'm not sure you're still listenting to or interested in this.
    Anyway I finally had some time to play with and come up with an implementation via system services.
    There are three files to make the service, whose codes are listed below.
    • main.m (wrapper executable)
    • main.rb (service body)
    • make (bash script to make .service from source)
    # Recipe
    1) Create the three plain text files (in utf8) by copy-pasting codes listed below and place them loose in a new directory, e.g., ~/Desktop/work.
    2) Issue the following commands in Terminal, which yield a package named TextHighlightServices.service in ~/Desktop/work.
    * You need to have gcc installed, which comes with Xcode.
    cd ~/Desktop/work
    chmod ug+x make
    ./make
    3) Move the TextHighlightServices.service to ~/Library/Serivecs
    4) Log out and log in to let the new service be recognised.
    (This may not be necessary for .service, but I'd play for safety. Also you may use the following command in Terminal instead of re-login, if necessary:
    # in 10.5
    /System/Library/CoreServices/pbs
    # in 10.6
    /System/Library/CoreServices/pbs -flush
    5) Done.
    # Usage
    If everything goes well, you'll see two services named "Text Highlight - Add" and "Text Highlight - Remove" in Services menu in TextEdit when you select some text in rich text mode. (In 10.6, services only appear in its applicable context, while in 10.5, they may yet appear in non-applicable context and be grayed-out.)
    Invoke the serivces on selected rich text via menu or keyboard shortcuts and see if it works. Keyboard shortcuts are currently defined as Command-9 for highlight and Command-0 for unhighlight.
    You may change the menu item names, keyboard shortcuts and highlight colour by changing the values in the #properties section at the beginning of make file. (Or you may directly edit Info.plist file in the package. But 'make' is instant and it'll be faster to re-make the package than to edit it manually)
    # Notes
    • Highlight and unhighlight are implemented as two services and you cannot assign one keyboard shortcut, e.g., Command-Y to both to toggle highlight state. (One 'toggle highlight service' is possible but you need to re-write the code as such)
    • Keyboard shortcut is case-sensitive. E.g., J means Command-Shift-j.
    • If keyboard shortcut is ignored, it is most likely that the key is already used for something else.
    • This service is written to terminate itself if idle for ca. 20 seconds. It will be re-launched on demand. To keep the service running is not a problem, usually, but I noticed this rubycocoa code constantly uses ca 1.1% CPU and decided not to let it waste energy. If you rewrite the code in Objective-C proper, it would be 0.0% CPU usage in idle.
    • Tested with 10.5.8 and 10.6.5.
    # Files
    main.m
    // file
    //     main.m
    // function
    //     wrapper executable to run Contents/Resources/main.rb
    // compile
    //     gcc -framework RubyCocoa -o PROGNAME main.m
    #import <RubyCocoa/RBRuntime.h>
    int main(int argc, const char *argv[])
        return RBApplicationMain("main.rb", argc, argv);
    main.rb
    # file
    #     main.rb
    # function
    #     to provide text highlight services
    require 'osx/cocoa'
    include OSX
    class Services < NSObject
        attr_reader :last_invoked
        def init()
            @last_invoked = NSDate.date
            self
        end
        # utility method
        def highlight_pboard_colour(option, pboard, colr)
            # int option : 0 = remove bg colour, 1 = add bg colour
            # NSPastedBoard *pboard : pasteboard passed via service
            # NSColor colr : background colour for highlight
            raise ArgumentError, "invalid option: #{option}" unless [0,1].include? option
            @last_invoked = NSDate.date
            # read rtf data from clipboard
            rtf = pboard.dataForType('public.rtf')
            # make mutable attributed string from rtf data
            docattr = OCObject.new
            mas = NSMutableAttributedString.alloc.objc_send(
                :initWithRTF, rtf,
                :documentAttributes, docattr)
            rase ArgumentError, "zero-length rtf is given" if mas.length == 0
            # add or remove background colour attribute
            r = NSMakeRange(0, mas.length)
            if option == 1
                mas.objc_send(
                    :addAttribute, NSBackgroundColorAttributeName,
                    :value, colr,
                    :range, r)
            elsif option == 0
                mas.objc_send(
                    :removeAttribute, NSBackgroundColorAttributeName,
                    :range, r)
            end
            mas.fixAttributesInRange(r)
            # make rtf data from mutable attributed string
            rtf = mas.objc_send(
                :RTFFromRange, r,
                :documentAttributes, docattr)
            # write rtf data to the clipboard
            pboard.objc_send(
                :declareTypes, ['public.rtf'],
                :owner, nil)
            pboard.objc_send(
                :setData, rtf,
                :forType, 'public.rtf')
        end
        # service method 1 : highlight rtf
        def highlight_userData_error(pboard, udata, error)
            # NSPastedBoard *pboard : pasteboard passed via service
            # NSString *udata : space delimited string of red, green, blue, alpha components to define background colour
            # NSString **error
            # set background colour from given user data
            r, g, b, a = udata.to_s.split(/\s+/).map {|x| x.to_f}
            colr = NSColor.objc_send(
                :colorWithCalibratedRed, r,
                :green, g,
                :blue, b,
                :alpha, a)
            # add background colour to rtf
            self.highlight_pboard_colour(1, pboard, colr)
        end
        # register ruby method as objc method
        objc_method(:highlight_userData_error, 'v@:@@^@')
        # service method 2 : un-highlight rtf
        def unhighlight_userData_error(pboard, udata, error)
            # NSPastedBoard *pboard : pasteboard passed via service
            # NSString *udata : space delimited string of red, green, blue, alpha components to define background colour
            # NSString **error
            self.highlight_pboard_colour(0, pboard, nil)
        end
        # register ruby method as objc method
        objc_method(:unhighlight_userData_error, 'v@:@@^@')
    end       
    class AppDelegate < NSObject
        def init()
            @services = Services.alloc.init
            @timer = NSTimer.objc_send(
                :timerWithTimeInterval, 5.0,  # periodic check interval [sec]
                :target, self,
                :selector, :idle,
                :userInfo, nil,
                :repeats, true)
            @TTL = 20.0  # time to live in idle [sec]
            self
        end
        def applicationDidFinishLaunching(notif)
            NSApp.setServicesProvider(@services)
            NSRunLoop.currentRunLoop.objc_send(
                :addTimer, @timer,
                :forMode, NSDefaultRunLoopMode)
        end
        def applicationShouldTerminate(sender)
            @timer.invalidate
            NSTerminateNow
        end
        def idle(timer)
            if @services.last_invoked.timeIntervalSinceNow < -@TTL
                NSApp.terminate(self)
            end
        end
    end
    def main
        app = NSApplication.sharedApplication
        delegate = AppDelegate.alloc.init
        app.setDelegate(delegate)
        app.run
    end
    if __FILE__ == $PROGRAM_NAME    # = if this file is the primary ruby program currently executed
        main
    end
    make
    #!/bin/bash
    # file
    #    make
    # function
    #    to make PROGNAME.service package from main.m and main.rb
    export LC_ALL=en_GB.UTF-8
    # properties
    PROGNAME="TextHighlightServices"
    EXECPATH="${PROGNAME}.service/Contents/MacOS/${PROGNAME}"
    BNDL_TYPE="APPL"
    BNDL_SIGNATURE="????"
    BNDL_VERSION="1.0"
    BUILD_VERSION="1"
    SRC_VERSION="10000"
    HIGHLIGHT_MENU_ITEM="Text Highlight - Add"
    HIGHLIGHT_KEY="9"
    UNHIGHLIGHT_MENU_ITEM="Text Highlight - Remove"
    UNHIGHLIGHT_KEY="0"
    HIGHLIGHT_COLOUR="1.0 1.0 0.6 1.0" # R B G A in [0.0, 1.0]
    # make package directories
    rm -rf "${PROGNAME}".service
    mkdir -p "${PROGNAME}".service/Contents/{MacOS,Resources}
    # make PkgInfo
    cat <<EOF > "${PROGNAME}.service/Contents/PkgInfo"
    ${BNDL_TYPE}${BNDL_SIGNATURE}
    EOF
    # make Info.plist
    cat <<EOF > "${PROGNAME}".service/Contents/Info.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>CFBundleDevelopmentRegion</key>
        <string>English</string>
        <key>CFBundleExecutable</key>
        <string>${PROGNAME}</string>
        <key>CFBundleIdentifier</key>
        <string>bubo-bubo.${PROGNAME}</string>
        <key>CFBundleInfoDictionaryVersion</key>
        <string>6.0</string>
        <key>CFBundleName</key>
        <string>${PROGNAME}</string>
        <key>CFBundlePackageType</key>
        <string>${BNDL_TYPE}</string>
        <key>CFBundleShortVersionString</key>
        <string>${BNDL_VERSION}</string>
        <key>CFBundleSignature</key>
        <string>${BNDL_SIGNATURE}</string>
        <key>CFBundleVersion</key>
        <string>${BNDL_VERSION}</string>
        <key>NSPrincipalClass</key>
        <string>NSApplication</string>
        <key>NSServices</key>
        <array>
            <dict>
                <key>NSPortName</key>
                <string>${PROGNAME}</string>
                <key>NSMessage</key>
                <string>highlight</string>
                <key>NSMenuItem</key>
                <dict>
                    <key>default</key>
                    <string>${HIGHLIGHT_MENU_ITEM}</string>
                </dict>
                <key>NSKeyEquivalent</key>
                <dict>
                    <key>default</key>
                    <string>${HIGHLIGHT_KEY}</string>
                </dict>
                <key>NSSendTypes</key>
                <array>
                    <string>NSRTFPboardType</string>
                </array>
                <key>NSReturnTypes</key>
                <array>
                    <string>NSRTFPboardType</string>
                </array>
                <key>NSTimeout</key>
                <string>10000</string>
                <key>NSUserData</key>
                <string>${HIGHLIGHT_COLOUR}</string>
                <key>NSRequiredContext</key>
                <dict>
                    <key>NSApplicationIdentifier</key>
                    <array>
                        <string>com.apple.TextEdit</string>
                    </array>
                </dict>
            </dict>
            <dict>
                <key>NSPortName</key>
                <string>${PROGNAME}</string>
                <key>NSMessage</key>
                <string>unhighlight</string>
                <key>NSMenuItem</key>
                <dict>
                    <key>default</key>
                    <string>${UNHIGHLIGHT_MENU_ITEM}</string>
                </dict>
                <key>NSKeyEquivalent</key>
                <dict>
                    <key>default</key>
                    <string>${UNHIGHLIGHT_KEY}</string>
                </dict>
                <key>NSSendTypes</key>
                <array>
                    <string>NSRTFPboardType</string>
                </array>
                <key>NSReturnTypes</key>
                <array>
                    <string>NSRTFPboardType</string>
                </array>
                <key>NSTimeout</key>
                <string>10000</string>
                <key>NSRequiredContext</key>
                <dict>
                    <key>NSApplicationIdentifier</key>
                    <array>
                        <string>com.apple.TextEdit</string>
                    </array>
                </dict>
            </dict>
        </array>
        <key>NSUIElement</key>
        <string>1</string>
    </dict>
    </plist>
    EOF
    # make version.plist
    cat <<EOF > "${PROGNAME}".service/Contents/version.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>BuildVersion</key>
        <string>${BUILD_VERSION}</string>
        <key>CFBundleShortVersionString</key>
        <string>${BNDL_VERSION}</string>
        <key>CFBundleVersion</key>
        <string>${BNDL_VERSION}</string>
        <key>ProjectName</key>
        <string>${PROGNAME}</string>
        <key>SourceVersion</key>
        <string>${SRC_VERSION}</string>
    </dict>
    </plist>
    EOF
    # make ServicesMenu.strings
    mkdir -p "${PROGNAME}".service/Contents/Resources/English.lproj
    cat <<EOF > "${PROGNAME}".service/Contents/Resources/English.lproj/ServicesMenu.strings
    /* Services menu item to highlight or unhighlight the selected text */
    "${HIGHLIGHT_MENU_ITEM}" = "${HIGHLIGHT_MENU_ITEM}";
    "${UNHIGHLIGHT_MENU_ITEM}" = "${UNHIGHLIGHT_MENU_ITEM}";
    EOF
    # copy *.rb in Contents/Resoures
    ditto *.rb "${PROGNAME}".service/Contents/Resources/
    # compile wrapper executable
    gcc -framework RubyCocoa -o "${EXECPATH}" main.m
    It is fun to play with rubycocoa.
    And glad if this helps.
    Good luck,
    H
    cf.
    http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/SysServices/SysService s.pdf
    Message was edited by: Hiroto ( fixed 'make' to './make' in Recipe 2, sorry)

  • How to define different styles to different levels of hierarchical titles?

    With difficulty, I found how to define a style for hierarchical titles, i.e.:
    1. First level
    1.1. Second level
    1.1.1. Third level
    etc.
    But all levels will have the same character parameters (font, size, etc).
    What I would like is, e.g.:
    1. First level
    1.1. Second level
    1.1.1. Third level
    In MS Word, it is easy: you define a different style for each level. In Pages, I found no way to do this, and no clue in the user's manual.
    Is it possible (I guess it should be), and if so, how?
    Thanks
    Éric

    You need to use the Styles Drawer. Go to: View > Show Styles Drawer. To define a Style, highlight the formatted text then click the plus sign at the bottom of the styles drawer. To delete a style, secondary click on the style and choose Delete Style.

  • Syntax Highlighting for LESS CSS in Dreamweaver CS5.5

    This article describes how to add the .less extension to Dreamweaver so that it views it as CSS and thus performs proper syntax highlighting.
    I'm using Dreamweaver CS5.5 and following those steps still doesn't work for me. It works perfectly fine in CS5 and earlier versions but not CS5.5.
    Do you have any ideas? I'm modifying the following file as the above link suggests:
    C:\Program Files (x86)\Adobe\Adobe Dreamweaver CS5.5\configuration\DocumentTypes\MMDocumentTypes.xml

    Aegis Kleais wrote:
    Sorry, Al, but I couldn't disagree more.  Where I respect the fact that, as coders, we're rather ingrained with our workflow processes and, at times, hesitant to change, I've found LESS' benefits to be very worthwhile.
    No need to apologize. Preprocessing is a topic on which there are differing opinions. You have one. I have one. There are advocates:
    http://blog.urbaninsight.com/2012/04/12/ten-reasons-you-should-be-using-css-preprocessor
    There are those who are not sold:
    http://blog.millermedeiros.com/the-problem-with-css-pre-processors/
    http://www.skybondsor.com/blog/css-preprocessors
    There are those mostly sold:
    http://css-tricks.com/musings-on-preprocessing/
    There are even those who have been converted (but who might reverse at some later point):
    http://cognition.happycog.com/article/preprocess-this
    Heck, even I might be converted someday - or not
    Bottom line for me, right now? I know I can write CSS that is better than most, more efficient than most, and easier to follow than most, and a preprocessor would add unwanted complexity. But that's for me. For someone not able to be organized intutively, or for a large - but carefully coordinated - team, a preprocessor could be a positive.
    But not for me.
    There are evolving trends - popular aspects of the technology that may and should find themselves being adapted into CSS. But I've been around this business as long as CSS has. I've seen buzzwords and trends and I've historically been spot-on in predicting the one that will stick. I think preprocessing will stick - but only insofar as it will be a catalyst for features in future versions of CSS. As a separate technology it makes no sense - to me

  • [SOLVED] syntax highlighting in vim

    Hi,
    How do you guys set syntax highlighting in your vimrc?  For example, I have a bunch of mutt config files saved as something like alias.muttrc, colors.muttc, etc... and I want them all to use the muttrc syntax.
    Currently, I have this in my vimrc:
    au BufNewFile,BufRead *.muttrc setf muttrc
    This works unless my first line is a comment (or first non-blank line).   Which is annoying because I want to begin with a comment sometimes!
    Also, I noticed that if my main config file--muttrc--is set correctly whether or not it begins with a comment.   (This file is already matched to muttrc syntax without my intervention).
    Does anyone have a better/different way of setting the syntax?
    Last edited by miggy (2009-05-27 16:15:44)

    Thanks for the suggestion but I'm experiencing the same behavior.  Something weird's going on.   Can someone confirm this same behavior?
    file1.muttrc
    color normal white default
    file2.muttrc
    # Comment
    color normal white default
    file3.muttrc
    color normal white default
    # Comment
    As I'm writing these, they all are good, but when I go to edit them, only file1.muttrc has the correct highlighting.  The others can get it if I say :set syntax=muttrc. 
    It's especially weird that the comments are highlighted but nothing else is.  If I'm not using any sort of file detecting then not even the comments are highlighted

  • /usr/share/nano/js.nanorc configuration: syntax highlighting

    I have a question regarding syntax highlighting with JavaScript using nano. I have tweaked the js.nanorc file to my liking using the colors I prefer:
    ## New updated taken from [url]http://wiki.linuxhelp.net/index.php/Nano_Syntax_Highlighting[/url]
    syntax "JavaScript" "\.(js)$"
    ## Default
    color brightgreen "^.+$"
    ## Decimal, cotal and hexadecimal numbers
    color brightyellow "\<[-+]?([1-9][0-9]*|0[0-7]*|0x[0-9a-fA-F]+)([uU][lL]?|[lL][uU]?)?\>"
    ## Floating point number with at least one digit before decimal point
    color brightyellow "\<[-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([EePp][+-]?[0-9]+)?[fFlL]?"
    color brightyellow "\<[-+]?([0-9]+[EePp][+-]?[0-9]+)[fFlL]?"
    ## Keywords
    color brightcyan "\<(break|case|catch|continue|default|delete|do|else|finally)\>"
    color brightcyan "\<(for|function|if|in|instanceof|new|null|return|switch)\>"
    color brightcyan "\<(switch|this|throw|try|typeof|undefined|var|void|while|with)\>"
    ## Type specifiers
    color brightmagenta "\<(Array|Boolean|Date|Enumerator|Error|Function|Math)\>"
    color brightmagenta "\<(Number|Object|RegExp|String)\>"
    color brightmagenta "\<(true|false)\>"
    ## String
    color brightblue "L?\"(\\"|[^"])*\""
    color brightblue "L?'(\'|[^'])*'"
    ## Escapes
    color red "\\[0-7][0-7]?[0-7]?|\\x[0-9a-fA-F]+|\\[bfnrt'"\?\\]"
    ## Comments
    color brightwhite start="/\*" end="\*/"
    color brightwhite "//.*$"
    However, I would also like the rendering to be a little different. For example:
    var code = function(nano) {
    console.log("I would like these parenthesis to be a different color than the keywords");
    The parenthesis and keywords(var, function, for, while....etc) are the same color, how can I adjust the rendering so that the parenthesis or brackets will be a different color?
    Last edited by rg_arc (2012-04-04 13:40:31)

    doug piston wrote:I deal with alot of .mk files and would love to see it there.
    You mean GNU makefiles?
    I'm afraid they might be out of scope for this generic config-file syntax.
    Logically they're not system config files, and technically they're a pretty specialized and complex format (different "types" of rules, rules spanning multiple lines, rules containing arbitrary Bash code, etc.).
    This is how an .mk file currently looks with this highlighting syntax:
    $ nano -Y conf /usr/lib/httpd/build/rules.mk
    And apart from highlighting variables of the form $$abc or $(abc), I'm not sure how much can be improved here without breaking the highlighting for more conventional config files.
    It would probably be better to create a specialized highlighting syntax just for .mk files.
    EDIT: I sat down and did just that, here's the result: nano syntax highlighting: GNU makefiles, and here is how the above makefile snipped looks with it:
    Last edited by sas (2012-02-01 15:18:52)

  • Nano syntax highlighting: catch-all syntax for configuration files

    After years of using nano, I only recently learned that it supports syntax coloring... (Why would they turn that off by default? ) Well, I thought I'll make up for it by making extra good use of it from now on...
    Unfortunately it didn't ship a highlighting syntax for the the kind of files that I use nano the most for: system configuration files.
    So I wrote my own, and after tweaking a bit here and there whenever I encountered a config file for which the highlighting wasn't satisfactory at first, I think the result is now good enough (screenshots below) that it's worth sharing with my fellow Arch users:
    Code & Instructions:
    Here is the syntax definition:
    # config file highlighting
    syntax "conf" "(\.(conf|config|cfg|cnf|rc|lst|list|defs|ini|desktop|mime|types|preset|cache|seat|service|htaccess)$|(^|/)(\w*crontab|mirrorlist|group|hosts|passwd|rpc|netconfig|shadow|fstab|inittab|inputrc|protocols|sudoers)$|conf.d/|.config/)"
    # default text
    color magenta "^.*$"
    # special values
    icolor brightblue "(^|\s|=)(default|true|false|on|off|yes|no)(\s|$)"
    # keys
    icolor cyan "^\s*(set\s+)?[A-Z0-9_\/\.\%\@+-]+\s*([:]|\>)"
    # commands
    color blue "^\s*set\s+\<"
    # punctuation
    color blue "[.]"
    # numbers
    color red "(^|\s|[[/:|<>(){}=,]|\])[-+]?[0-9](\.?[0-9])*%?($|\>)"
    # keys
    icolor cyan "^\s*(\$if )?([A-Z0-9_\/\.\%\@+-]|\s)+="
    # punctuation
    color blue "/"
    color brightwhite "(\]|[()<>[{},;:=])"
    color brightwhite "(^|\[|\{|\:)\s*-(\s|$)"
    # section headings
    icolor brightyellow "^\s*(\[([A-Z0-9_\.-]|\s)+\])+\s*$"
    color brightcyan "^\s*((Sub)?Section\s*(=|\>)|End(Sub)?Section\s*$)"
    color brightcyan "^\s*\$(end)?if(\s|$)"
    # URLs
    icolor green "\b(([A-Z]+://|www[.])[A-Z0-9/:#?&$=_\.\-]+)(\b|$| )"
    # XML-like tags
    icolor brightcyan "</?\w+((\s*\w+\s*=)?\s*("[^"]*"|'[^']*'|!?[A-Z0-9_:/]))*(\s*/)?>"
    # strings
    color yellow "\"(\\.|[^"])*\"" "'(\\.|[^'])*'"
    # comments
    color white "#.*$"
    color blue "^\s*##.*$"
    color white "^;.*$"
    color white start="<!--" end="-->"
    To install, save the above above code snippet as a file called conf.nanorc in the folder /usr/share/nano/ (or /usr/local/share/nano/ or similar if you feel strongly about the /usr <--> /usr/local separation), and then add the following to the end of the file /etc/nanorc:
    ## Configuration files (catch-all syntax)
    include "/usr/share/nano/conf.nanorc"
    Hints:
    The colors I chose look good (imo) with the terminal background and color settings that I use, but might not look good, or even readable, with yours, so simply change the color names in the code snippet to whatever you prefer - valid color names are:
    If you use a console with white background, you'll have to change at least the white color I chose for comments and punctuation.
    The first code line in the snippet includes a regular expression that defines for which file names this syntax highlighting should be used. Whenever you encounter a config file that is not matched by this, but you would still like to open it with syntax highlighting, you can manually select this syntax with nano's -Y switch, like so:
    nano -Y conf myConfigFile
    Technical Note:
    It's implemented as a single catch-all syntax, since nano chooses which syntax to apply based on the filename, and in the case of config files usually not much can be learned about the content format from the file name extension (.conf can by anything from flat key/value tuples to XML, .ini can be the official INI format or something else, etc...).
    This means that some compromises have been made, so with this highlighting syntax probably no config file looks 100% as good as a highlighting syntax that would be specifically optimized for one kind of config format, but all in all the vast majority of config files should look pretty good.
    Screenshots:
    /etc/rc.conf,  /etc/hosts:
    /etc/pacman.conf,  /etc/group:
    xorg.conf,  some .desktop file:
    httpd.conf (Apache config),  php.ini:
    More screenshots:
    /etc/fonts/fonts.conf (uses XML)
    /etc/inittab
    /etc/fstab
    /etc/inputrc
    /etc/mime.types
    /etc/protocols
    /etc/xinetd.conf
    See Also:
    nano syntax highlighting: GNU makefiles
    Update [2012-01-28]: Made some more improvements to the syntax definition (see post)
    Last edited by sas (2012-02-01 15:26:43)

    doug piston wrote:I deal with alot of .mk files and would love to see it there.
    You mean GNU makefiles?
    I'm afraid they might be out of scope for this generic config-file syntax.
    Logically they're not system config files, and technically they're a pretty specialized and complex format (different "types" of rules, rules spanning multiple lines, rules containing arbitrary Bash code, etc.).
    This is how an .mk file currently looks with this highlighting syntax:
    $ nano -Y conf /usr/lib/httpd/build/rules.mk
    And apart from highlighting variables of the form $$abc or $(abc), I'm not sure how much can be improved here without breaking the highlighting for more conventional config files.
    It would probably be better to create a specialized highlighting syntax just for .mk files.
    EDIT: I sat down and did just that, here's the result: nano syntax highlighting: GNU makefiles, and here is how the above makefile snipped looks with it:
    Last edited by sas (2012-02-01 15:18:52)

  • Add extra colors to syntax highlighting?

    Is there a file or some code I could make in order to add an extra color or two for syntax highlighting? Like having a certain color for function names and a different one for numbers etc.?

    Hi,
    There is an application Preferences for ActionScript called Syntax colors where you can specify a code coloring for Keywords, comments,identifiers & strings. You can access this on Windows by Edit>Preferences>ActionScript & on Mac by Flash>Preferences>ActionScript. Let me know if this helps you.
    Thanks!

  • Syntax Highlighting in nano?

    After seeing nano running on a Linux machine while editing a python file I realised that it was different from my mac version which lacked the beautful syntax highlighting. Anyway to get syntax highlighting? and update the nano version? -Cheers

    How to use syntax highlighting with the GNU nano text editor

  • Request: Syntax Highlighting

    I'd liek to be able to amend the lists of words that fall in the different syntax categories for highlighting. Many words (such as NOTFOUND, BOOLEAN, BINARY_INTEGER, TRUNC to name a few) are not highlighted and I'd like to add the words to the syntax list.

    The syntax highlighter doesn't work on a simple list of words, it does a full parse of the text. The only people who can amend it are the development team.
    Keep reporting missing keywords so they include them in any subsequent amendments.
    If you've got a metalink account, report them as bugs.

  • Repainting question for my syntax highlighter

    Hello there,
    I have a syntax highlighter which reuses much of the very useful code developed by Claude Dugauy, which can be found at http://www.fawcette.com/javapro/2003_07/magazine/columns/visualcomponents/default_pf.aspx
    . The syntax highlighting uses regular expressions, so its easily extendable to meet your needs.
    However, there is one problem: whenever the user presses a key, the whole of the TextPane containing the highlighted text, is repainted in its entirety. This is fine for small amounts of text to be highlighted, but is very slow when it comes to 1000+ lines.
    Please could someone be so excellent as to tell me how to go about addressing this problem, so that only a small amount of text is repainted whenever the user types something into the TextPane e.g. that inside the current viewport, or just the last typed word - thus removing this problem of inefficiency.
    Thanks in advance,
    Edd.

    I don't think it's going to be that easy. Every time a change is made, the default style is applied to the whole document, then the whole document is copied into a String so it can be reparsed and have the syntax styles applied again. Even if you could limit what actually gets painted, you'd still have all that unnecessary work going on.
    You could try forcing the highlighter to only reparse a portion of the document--like,say, a hundred lines before and after the point where the edit occurred--but deciding exactly where to start and stop can be pretty tricky.

Maybe you are looking for

  • Asset accounting (urgent)

    Hi Guru's Asset 474973 depreciation is not calculating correctly A write up was put on the asset in the month of January, then the depreciation was re-run, in total on the master data of the asset,  the planed values for the year showing  correct onl

  • Time Machine back up with hard drive connected to D-Link DIR-655

    Recently D-Link updated the share port utility with a mac version. I have heard that Time Machine does not easily recognize network shared hard drives but to my surprise this morning it did. With using the new software and hooking up my hard drive to

  • Mac running slow dock file

    Hi everyone today I have a question about my Mac it is on version 10.7.5 It has 4 gb of ram and 1 tv of hard drive The problem I have is my account only is running slow and I check activity monitor and one process called dock is taking 99%-99.9% of m

  • Webdynpro call another web page

    Hi experts, can my webdynpro call another web page? I need that the webdynpro call a pop-up to another web page and when this page is closed a variable returns to webdynpro to process. Is this possible? Thanks in advance, David

  • Change computer name

    my mac book was originally bought by my brother, therefore the computer always says"John Maguire's Computer" is it possible to change this? Thanks