Change Sublime Text 3 Bracket/Indent Rules - sublimetext

In Sublime Text 3, I want to change auto bracket rules.
By default, I get this
class extends Parent implements Interface {
}
but I want this
class extends Parent implements Interface
{
}
how can I accomplish this.

You can just create a new snippet, and put it in your user package folder.
The original snippet that ships with Sublime Text is:
<snippet>
<content><![CDATA[class ${1:${TM_FILENAME/(.*?)(\..+)/$1/}} ${2:extends ${3:Parent} }${4:implements ${5:Interface} }{
$0
}]]></content>
<tabTrigger>cl</tabTrigger>
<scope>source.java</scope>
<description>javaclass</description>
</snippet>
You can create a new one and move the opening parenthesis down where you want it
<snippet>
<content><![CDATA[class ${1:${TM_FILENAME/(.*?)(\..+)/$1/}} ${2:extends ${3:Parent} }${4:implements ${5:Interface} }
{
$0
}]]></content>
<tabTrigger>cl</tabTrigger>
<scope>source.java</scope>
<description>javaclass</description>
</snippet>

Related

Silverstripe - Turn modules on or off in config

Is it possible to activate or deactivate modules based on entries in either config.yml or _config.php?
Say I've built an Image Gallery module but don't want it showing on the site yet, can it be deactivated in the config files?
Only if the module has provided functionality to do so.
You can add your own private static $enable_module = true
class MyClass extends Object
{
private static $enable_module = true;
public function doMyThing()
{
if (!Config::inst()->forClass('MyClass')->enable_module) {
return false;
}
// do stuff here
}
}
then you can disable it via YML
MyClass:
enable_module: false
would disable it.
For templates you could add
public function getGalleryEnabled() {
return Config::inst()->forClass('MyClass')->enable_module;
}
to your Page_Controller class and then
<% if $GalleryEnabled %><% include MyGallery %><% end_if %>
The best practice is: never develop on the live site
SilverStripe scans all directories in webroot for modules. If you place a file called manifest_exclude in any directory, it won't be scanned and not included; the autoloader won't find it and you cannot call your class without including the file manually.

UWP - Inherit from Base Page C#

I'm one of the many windows app developers. I'm sure someone other ran in this problem too. I want to have a base page (c#) where I add methods and use it in some pages without coding it over and over.
I've tried it like this:
Basicpage.cs:
public class BasicPage : Page
{
public void Test() {
}
}
SettingsPage.xaml.cs:
public sealed partial class SettingsPage : BasicPage{
public SettingsPage () {
InitializeComponent();
}
}
On the bold "BasicPage" there are the errors:
Base class of "...SettingsPage" differs from declared in other parts
and
Base type 'BasicPage' is already specified in other parts
Does someone know a solution?
I assume SettingsPage has a XAML part, which also needs to be derived from BasicPage:
<local:BasicPage x:Class="MyNamespace.SettingsPage" ...>
<!-- settings page content -->
</local:BasicPage>

Thymeleaf + Spring : How to keep line break?

I'm using Thymeleaf template engine with spring and I'd like to display text stored throught a multiline textarea.
In my database multiline string are store with "\n" like this : "Test1\nTest2\n...."
With th:text i've got : "Test1 Test2" with no line break.
How I can display line break using Thymeleaf and avoid manually "\n" replacing with < br/> and then avoid using th:utext (this open form to xss injection) ?
Thanks !
Two of your options:
Use th:utext - easy setup option, but harder to read and remember
Create a custom processor and dialect - more involved setup, but easier, more readable future use.
Option 1:
You can use th:utext if you escape the text using the expression utility method #strings.escapeXml( text ) to prevent XSS injection and unwanted formatting - http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#strings
To make this platform independent, you can use T(java.lang.System).getProperty('line.separator') to grab the line separator.
Using the existing Thymeleaf expression utilities, this works:
<p th:utext="${#strings.replace( #strings.escapeXml( text ),T(java.lang.System).getProperty('line.separator'),'<br />')}" ></p>
Option 2:
The API for this is now different in 3 (I wrote this tutorial for 2.1)
Hopefully you can combine the below logic with their official tutorial. One day maybe I'll have a minute to update this completely. But for now:
Here's the official Thymeleaf tutorial for creating your own dialect.
Once setup is complete, all you will need to do to accomplish escaped textline output with preserved line breaks:
<p fd:lstext="${ text }"></p>
The main piece doing the work is the processor. The following code will do the trick:
package com.foo.bar.thymeleaf.processors
import java.util.Collections;
import java.util.List;
import org.thymeleaf.Arguments;
import org.thymeleaf.Configuration;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Node;
import org.thymeleaf.dom.Text;
import org.thymeleaf.processor.attr.AbstractChildrenModifierAttrProcessor;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.unbescape.html.HtmlEscape;
public class HtmlEscapedWithLineSeparatorsProcessor extends
AbstractChildrenModifierAttrProcessor{
public HtmlEscapedWithLineSeparatorsProcessor(){
//only executes this processor for the attribute 'lstext'
super("lstext");
}
protected String getText( final Arguments arguments, final Element element,
final String attributeName) {
final Configuration configuration = arguments.getConfiguration();
final IStandardExpressionParser parser =
StandardExpressions.getExpressionParser(configuration);
final String attributeValue = element.getAttributeValue(attributeName);
final IStandardExpression expression =
parser.parseExpression(configuration, arguments, attributeValue);
final String value = (String) expression.execute(configuration, arguments);
//return the escaped text with the line separator replaced with <br />
return HtmlEscape.escapeHtml4Xml( value ).replace( System.getProperty("line.separator"), "<br />" );
}
#Override
protected final List<Node> getModifiedChildren(
final Arguments arguments, final Element element, final String attributeName) {
final String text = getText(arguments, element, attributeName);
//Create new text node signifying that content is already escaped.
final Text newNode = new Text(text == null? "" : text, null, null, true);
// Setting this allows avoiding text inliners processing already generated text,
// which in turn avoids code injection.
newNode.setProcessable( false );
return Collections.singletonList((Node)newNode);
}
#Override
public int getPrecedence() {
// A value of 10000 is higher than any attribute in the SpringStandard dialect. So this attribute will execute after all other attributes from that dialect, if in the same tag.
return 11400;
}
}
Now that you have the processor, you need a custom dialect to add the processor to.
package com.foo.bar.thymeleaf.dialects;
import java.util.HashSet;
import java.util.Set;
import org.thymeleaf.dialect.AbstractDialect;
import org.thymeleaf.processor.IProcessor;
import com.foo.bar.thymeleaf.processors.HtmlEscapedWithLineSeparatorsProcessor;
public class FooDialect extends AbstractDialect{
public FooDialect(){
super();
}
//This is what all the dialect's attributes/tags will start with. So like.. fd:lstext="Hi David!<br />This is so much easier..."
public String getPrefix(){
return "fd";
}
//The processors.
#Override
public Set<IProcessor> getProcessors(){
final Set<IProcessor> processors = new HashSet<IProcessor>();
processors.add( new HtmlEscapedWithLineSeparatorsProcessor() );
return processors;
}
}
Now you need to add it to your xml or java configuration:
If you are writing a Spring MVC application, you just have to set it at the additionalDialects property of the Template Engine bean, so that it is added to the default SpringStandard dialect:
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean class="com.foo.bar.thymeleaf.dialects.FooDialect"/>
</set>
</property>
</bean>
Or if you are using Spring and would rather use JavaConfig you can create a class annotated with #Configuration in your base package that contains the dialect as a managed bean:
package com.foo.bar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.foo.bar.thymeleaf.dialects.FooDialect;
#Configuration
public class TemplatingConfig {
#Bean
public FooDialect fooDialect(){
return new FooDialect();
}
}
Here are some further references on creating custom processors and dialects: http://www.thymeleaf.org/doc/articles/sayhelloextendingthymeleaf5minutes.html , http://www.thymeleaf.org/doc/articles/sayhelloagainextendingthymeleafevenmore5minutes.html and http://www.thymeleaf.org/doc/tutorials/2.1/extendingthymeleaf.html
Try putting style="white-space: pre-line" on the element.
For example:
<span style="white-space: pre-line" th:text="${text}"></span>
You might also be interested in white-space: pre-wrap which also maintains consecutive spaces in addition to line breaks.
Avoid using th:utext if possible as it has serious security implications. If care is not taken, th:utext can create the possibility of XSS attacks.
Maybe not what the OP had in mind, but this works and prevents code injection:
<p data-th-utext="${#strings.replace(#strings.escapeXml(text),'
','<br>')}"></p>
(Using HTML5-style Thymeleaf.)
In my case escapeJava() returns unicode values for cyrillic symbols, so I wrap all in unescapeJava() method help to solve my problem.
<div class="text" th:utext="${#strings.unescapeJava(#strings.replace(#strings.escapeJava(comment.text),'\n','<br />'))}"></div>
If you are using jQuery in thymleaf, you can format your code using this:
$('#idyourdiv').val().replace(/\n\r?/g, '<br />')
Hope that answer can help you
Try this
<p th:utext="${#strings.replace(#strings.escapeJava(description),'\n','<br />')}" ></p>
You need to use th:utext and append break line to string.
My code is:
StringBuilder message = new StringBuilder();
message.append("some text");
message.append("<br>");
message.append("some text");
<span th:utext="${message}"></span>
Inspired by #DavidRoberts answer, I made a Thymeleaf dialect that makes it easy to keep the line breaks, if the css white-space property isn't an option.
It also bring support for BBCode if you want it.
You can either import it as a dependency (it's very light, and very easy to set up thanks to the starter project) or just use it as inspiration to make your own.
Check it out here :
https://github.com/oxayotl/meikik-project

using resharper to extract a class and introduce a constructor dependency

Is it possible to use Resharper to refactor code such that the below method Eat is extracted into a seperate class, and the newly extracted class is injected in the Dinner class as an external dependency?
Original Code
public class Dinner
{
public Dinner()
{
}
public void Eat()
{
//do the eating
}
}
Refactored Code
public interface IEatService
{
void Eat();
}
public class EatService : IEatService
{
public void Eat()
{
}
}
public class Dinner
{
private readonly IEatService _eatService = null;
public Dinner(IEatService eatService)
{
_eatService = eatService;
}
public void Eat()
{
_eatService.Eat();
}
}
It doesn't have to be exactly as the refactored code - this is shown to give an idea.
You can do it nearly as you want in R# 7 using three-step refactoring:
Place the caret at your Eat method, invoke Extract Class refactoring (Ctrl-Shift-R in VS), name your class EatService.
Place the caret at your EatService class, invoke Extract Interface refactoring.
Place the caret at your EatService class, invoke Use Base type Where Possible refactoring.
All that is left is to fix a constructor in Dinner class so it would get IEatService as a parameter.
Using R# 6, one way to achieve this would be with this sequence of operations. Note that refactorings are available on both ReSharper | Refactor on the menu bar, or (quicker) in context with Ctrl+Shift+R. There's still a bit of typing; I wouldn't be surprised if there were a way that didn't require you to type anything at all.
Start with your Original Code in a file named Dinner.cs
With the cursor on Eat, user the Extract Interface refactoring, naming the interface IEatService
With the cursor on IEatService, Alt+Enter and create a derived type, accepting the offered name of EatService, and Alt+Enter to fill in the method implementation body
Here's where we have to type: In Dinner.Eat(), type _eatService.Eat();. Note that _eatService is red; Alt+Enter on it, choose 'Create field', change the offered type to IEatService
With the cursor on the definition of _eatService, Alt+Enter and choose 'Initialize from ctor paramater, and then Alt+Enter again and accept the readonly suggestion
Note that initialising _eatService to null is redundant; R# would let you know this.
We're now at your target code.
I think R# 7 has some new refactorings (such as Extract Class) which might make this quicker.

Adding a custom editor to visual studio editor list

I am in the process of writing a custom editor for visual studio. I have implemented some basic functionality for the new language e.g. syntax highlighting and I succesfully installed tha package by using the generated .vsix file. All works just nice, however my custom editor needs to be able to be associated with different file extensions.
I thought, mistakenly, that since I installed the editor it would appear under
Tools->Options..->Text Editor->File Extension->Editors list:
However it does not appear there. So the question is: how do you add a custom editor to this list?
Thanks for any help!
Well at least I got the tumbleweed badge for this question.
After a lot of reverse engineering I found the solution... which is not documented.. Anywhere..
Step number 1:
First you need to create an editor factory with all the bells and whistles it comes with - MSVS has an extension for it.
Step number 2:
Then you have to create such a class
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
class ProvideFileExtensionMapping : RegistrationAttribute
{
private readonly string _name, _id, _editorGuid, _package;
private readonly int _sortPriority;
public ProvideFileExtensionMapping(string id, string name, object editorGuid, string package, int sortPriority)
{
_id = id;
_name = name;
if (editorGuid is Type)
{
_editorGuid = ((Type)editorGuid).GUID.ToString("B");
}
else
{
_editorGuid = editorGuid.ToString();
}
_package = package;
_sortPriority = sortPriority;
}
public override void Register(RegistrationContext context)
{
using (Key mappingKey = context.CreateKey("FileExtensionMapping\\" + _id))
{
mappingKey.SetValue("", _name);
mappingKey.SetValue("DisplayName", _name);
mappingKey.SetValue("EditorGuid", _editorGuid);
mappingKey.SetValue("Package", _package);
mappingKey.SetValue("SortPriority", _sortPriority);
}
}
public override void Unregister(RegistrationAttribute.RegistrationContext context)
{
}
}
Step 3:
Then you need to add this class as an attribute to your editor factory (which you created in step 1):
[ProvideFileExtensionMapping("{E23E32ED-3467-4401-A364-1352666A3502}", "RText Editor", typeof(EditorFactory), GuidList.guidRTextEditorPluginEditorFactoryString, 100)]
public sealed class EditorFactory : IVsEditorFactory, IDisposable{...}
That's it. You should now be able to see your editor in the list of editors in visual studio.
Your editor shall be invoked when the file mapping is right.
Hopefully this post saves a lot of time for someone else..

Resources