When indenting java code with annotations, vim insists on indenting like this:
#Test
public void ...
I want the annotation to be in the same column as the method definition but I can't seem to find a way to tell vim to do that, except maybe using an indent expression but I'm not sure if I can use that together with regular cindent.
edit: The filetype plugin was already turned on I just got a bit confused about indenting plugins. The accepted answer may be a bit hackish but works for me as well.
You shouldn't modify the built-in vim settings. Your changes could disappear after a package upgrade. If you copy it to your .vim, then you won't get any java indent bug fixes.
Instead, put the following into a new file called ~/.vim/after/indent/java.vim
function! GetJavaIndent_improved()
let theIndent = GetJavaIndent()
let lnum = prevnonblank(v:lnum - 1)
let line = getline(lnum)
if line =~ '^\s*#.*$'
let theIndent = indent(lnum)
endif
return theIndent
endfunction
setlocal indentexpr=GetJavaIndent_improved()
That way it loads the stock java indent and only modifies the indent to remove the annotation indents.
Edit: I cannot delete my own answer because it has already been accepted, but #pydave's answer seems to be the better (more robust) solution.
You should probably be using the indentation file for the java FileType (instead of using cindent) by setting filetype plugin indent on.
That said, the indentation file coming with the Vim 7.1 from my linux distribution (looking at the current vim svn this is still true for 7.2) doesn't account for annotations yet. I therefore copied /usr/share/vim/vim71/indent/java.vim (see https://vim.svn.sourceforge.net/svnroot/vim/branches/vim7.1/runtime/indent/java.vim) to ~/.vim/indent/java.vim and added the following lines right before the end:
let lnum = prevnonblank(v:lnum - 1)
let line = getline(lnum)
if line =~ '^\s*#.*$'
let theIndent = indent(lnum)
endif
I'm not sure if this breaks any of the other indentations, but it works for me.
I found pydave's suggestion almost what I wanted, but I wanted this:
#Override
public void ...
and this:
#Override public void ...
so I replaced the regex (as per pydave's, place in ~/.vim/after/indent/java.vim):
setlocal indentexpr=GetJavaIndent_improved()
function! GetJavaIndent_improved()
let theIndent = GetJavaIndent()
let lnum = prevnonblank(v:lnum - 1)
let line = getline(lnum)
if line =~ '^\s*#[^{]*$'
let theIndent = indent(lnum)
endif
return theIndent
endfunction
Related
I want to use javaaddpath with different path to be added on my linux and window computer.
However, I want it to be true dynamic allocation. In other words, user can define his/her own Path_Str = ' ....../ParforProgMonv2/java' and pass it at this step: pctRunOnAll javaaddpath (Path_Str)
After opening matlab pool, I want to do something like this:
if strcmp(MonitorProcess, 'Yes')
%add this line for progress monitor
pctRunOnAll javaaddpath ('/home/dkumar/ParforProgMonv2/java')
end
However, rather than fixed path '/home/dkumar/ParforProgMonv2/java', I would like to include dynamic path chosen between
'/home/dkumar/ParforProgMonv2/java' or 'C:/Users/DK_GS/ParforProgMonv2/java'
depending on whether it's my window computer or linux.
I tried to follow this solution using ClassPathHacker.java; however, did not understand it.
Some help would be appreciated.
Would something like this work?
searchpath = 'ParforProgMonv2/java'; % Directory to search for
if strcmp(MonitorProcess, 'Yes')
switch computer
case {'PCWIN', 'PCWIN64'}
% 32 or 64 bit Windows
% Use the system command to return all directories found on the machine
% that match your search directory. Use a regex to clean up the list
[~, cmdout] = system(['dir /s/b/AD | find "' searchstr '"');
allpaths = regexp(cmdout, '(.:\\[\w\-\\. ]+\w+(?=\s))', 'match'); % Split directory names, 1st cell should be the top level
pctRunOnAll javaaddpath (allpaths{1})
case 'GLNXA64'
% Linux
pctRunOnAll javaaddpath ('/home/dkumar/ParforProgMonv2/java')
otherwise
% Insert error handling here
end
end
Where computer returns a string specifying the computer type that is currently running.
EDIT: Per your comment I would recommend adding in a method to search for your filepath and return a string. I've added a sample for Windows; I'm not familiar enough with Linux to translate properly.
I need to pass two params in a java file similar as I pass from command line.
Something like
$ENV{classpath} = ".\\my.jar;$ENV{classpath}";
system("$ENV{JAVA_HOME}\\bin\\java com.myclass param1 param2" );
how can i achieve this in a perl script?
I don't have access to my work system still let me give it a try. It should work for you.
my $cpJava=" -cp /your/classpath";
my $myClass="your class name";
my $runMe="Java path ".$cpJava." ".$myClass." ".join(' ', #ARGV);
#ARGV will have all your parameters. Learn more about join from here.
Then use system:
system($runMe);
Hope it would work for you.
I am not sure why is it giving this error. Braces seem to be right. Another thing is that the same program works in Windows-eclipse but not in eclipse for Mac. What could be the reason?
import java.util.Vector;
public class Debug
{
private int something = 0;
private Vector list = new Vector();
public void firstMethod()
{
thirdMethod(something);
something = something + 1;
}
public void secondMethod()
{
thirdMethod(something);
something = something + 2;
}
public void thirdMethod(int value)
{
something = something + value;
}
public static void main(String[] args)
{
Debug debug = new Debug();
debug.firstMethod();
debug.secondMethod();
}
}
Ah, ok - it's probably a control-Z or other unprintable character at the end of the file that is ignored in Windows but not on the Mac. You copied the source from Windows to the Mac. Delete the last few characters and re-enter them - I think it will go away. I don't do Mac, though - I'm just guessing.
I had the same problem importing my projects from mac to linux Slackware.
Mac OSX creates some temporary files with the same name of the files in folders (._filename) in all folders.
Usually these files are invisible in Mac OSX, but in the other OSs no.
Eclipse can find these files and tries to handle like sources (._filename.java).
I solved deleting these files.
Only way i could resolve this problem was press Ctrl+A to select all text of file then Ctrl+C to copy them then delete file and create new class with intellij idea then Ctrl+P to paste text in new file. this resolve my problem and compiler never show error after do this solution.
It can happen when we copy and paste .It happens when there may be some character which is unrecognized in one platform but recognized in other.
I would suggest don't copy rather try to write the entire code by yourself. It should work
I got the same error when I imported a project I created in a Mac, to Windows. As #Massimo says Mac creates ._filename,java files which eclipse running in windows consider as source files. This is what causes the problem.
They are hidden files, which you can see when you select the option, "Show hidden files and folders" under folder options in Windows machine. Deleting these files solves the problem.
I got this message trying to call a subjob from a tRunJob component. In the tRunJob I had both checked "transmit whole context" AND listed individual parameters in the parameters/values box. Once I removed the additional parameters it worked.
There are probably hidden characters in the line. If you move your cursor through the characters and your cursor doesn't move in one character, that means there is an invalid character in the line. Delete those and it should work. Also try copying and pasting the line to an hex editor and you will see the invalid characters in it.
i face this problem many times in eclipse . What i found is that select all code - cut it using Ctrl + x and then save the file and again paste the code using Ctrl + V . This works for me many times when i copy the code from another editor.
I also faced similar issue while copying the code from one machine to another.
The issue was with Space only you need to identify the red mark in your eclipse code.
On Windows, if you copy the source to Notepad - save the file (as anything), ensuring ASCI encoding is selected - the character will be converted to a question-mark which you can then delete - then copy the code back to Eclipse.
In eclipse right click on the file -> Properties -> resources
In Text file encoding select US-ASCII
This way you will see all the special char, you can then find & replace
And then format the code
I know. Heresy. But I'm in a bind. I have a lot of config files that use absolute path names, which creates an incompatibility between OS X and Windows. If I can get OS X (which I'm betting is the more flexible of the two) to recognize Q:/foo/bar/bim.properties as a valid absolute file name, it'll save me days of work spelunking through stack traces and config files.
In the end, I need this bit of Java test code to print "SUCCESS!" when it runs:
import java.io.*;
class DriveLetterTest {
static public void main(String... args) {
File f = new File("S:");
if (f.isDirectory()) {
System.out.println("SUCCESS!");
} else {
System.out.println("FAIL!");
}
}
}
Anyone know how this can be done?
UPDATE: Thanks for all the feedback, everyone. It's now obvious to me I really should have been clearer in my question.
Both the config files and the code that uses them belong to a third-party package I cannot change. (Well, I can change them, but that means incurring an ongoing maintenance load, which I want to avoid if at all possible.)
I'm in complete agreement with all of you who are appalled by this state of affairs. But the fact remains: I can't change the third-party code, and I really want to avoid forking the config files.
Short answer: No.
Long answer: For Java you should use System.getProperties(XXX).
Then you can load a Properties file or Configuration based on what you find in os.name.
Alternate Solution just strip off the S: when you read the existing configuration files on non-Windows machines and replace them with the appropriate things.
Opinion: Personally I would bite the bullet and deal with the technical debt now, fix all the configuration files at build time when the deployment for OSX is built and be done with it.
public class WhichOS
{
public static void main(final String[] args)
{
System.out.format("System.getProperty(\"os.name\") = %s\n", System.getProperty("os.name"));
System.out.format("System.getProperty(\"os.arch\") = %s\n", System.getProperty("os.arch"));
System.out.format("System.getProperty(\"os.version\") = %s\n", System.getProperty("os.version"));
}
}
the output on my iMac is:
System.getProperty("os.name") = Mac OS X
System.getProperty("os.arch") = x86_64
System.getProperty("os.version") = 10.6.4
Honestly, don't hard-code absolute paths in a program, even for a single-platform app. Do the correct thing.
The following is my wrong solution, saved to remind myself not to repeat giving a misdirected advice ... shame on me.
Just create a symbolic link named Q: just at the root directory / to / itself.
$ cd /
$ ln -s / Q:
$ ln -s / S:
You might need to use sudo. Then, at the start of your program, just chdir to /.
If you don't want Q: and S: to show up in the Finder, perform
$ /Developer/Tools/SetFile -P -a V Q:
$ /Developer/Tools/SetFile -P -a V S:
which set the invisible-to-the-Finder bit of the files.
The only way you can replace java.io.File is to replace that class in rt.jar.
I don't recommend that, but the best way to do this is to grab a bsd-port of the OpenJDK code, make necessary changes, build it and redistribute the binary with your project. Write a shell script to use your own java binary and not the built-in one.
PS. Just change your config files! Practice your regex skills and save yourself a lot of time.
If you are not willing to change your config file per OS, what are they for in first place?
Every installation should have its own set of config files and use it accordingly.
But if you insist.. you just have to detect the OS version and if is not Windows, ignore the letter:
Something along the lines:
boolean isWindows = System.getProperty("os.name").toLowerCase()
.contains("windows");
String folder = "S:";
if (isWindows && folder.matches("\\w:")) {
folder = "/";
} else if (isWindows && folder.matches("\\w:.+")) {
folder = folder.substring(2);// ignoring the first two letters S:
}
You get the idea
Most likely you'd have to provide a different java.io.File implementation that can parse out the file paths correctly, maybe there's one someone already made.
The real solution is to put this kind of stuff (hard-coded file paths) in configuration files and not in the source code.
Just tested something out, and discovered something interesting: In Windows, if the current directory is on the same logical volume (i.e. root is the same drive letter), you can leave off the drive letter when using a path. So you could just trim off all those drive letters and colons and you should be fine as long as you aren't using paths to items on different disks.
Here's what I finally ended up doing:
I downloaded the source code for the java.io package, and tweaked the code for java.io.File to look for path names that start with a letter and a colon. If it finds one, it prepends "/Volumes/" to the path name, coughs a warning into System.err, then continues as normal.
I've added symlinks under /Volumes to the "drives" I need mapped, so I have:
/Volumes/S:
/Volumes/Q:
I put it into its own jar, and put that jar at the front of the classpath for this project only. This way, the hack affects only me, and only this project.
Net result: java.io.File sees a path like "S:/bling.properties", and then checks the OS. If the OS is OS X, it prepends "/Volumes/", and looks for a file in /Volumes/S:/bling.properties, which is fine, because it can just follow the symlink.
Yeah, it's ugly as hell. But it gets the job done for today.
Is there a plugin or tool in IntelliJ that will strip all comments out of your source .java files? I've read about an ANT task that can do this.. was looking to do the same from within the IDE. Alternatively a TextPad plugin would work as well..
You can use the "Replace" (or "Replace in Path" if you want to remove comments in multiple files) in the regular expression mode and then use this regular expression in the "Text to find" field:
(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/|[ \t]*//.*)
and replace it with an empty string. Then press "All" to apply this replacement to the entire file or all the selected files. This will remove all block comments and line comments from your file. If you want only block comments to be removed, use this regex instead:
(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)
And if you want to just remove line comments, you can use this regex:
([ \t]*//.*)
However, I should warn that this works only %99.99 of times. You might have a string variable defined in your file like:
String myStr = "/** I am not a comment */";
This regex will turn this to:
String myStr = "";
Late to the party but there is "Structural Search and Replace Dialogs" option that can be used to search different kind of comments and replace them
Go to Edit => Find => Replace Structurally...
Enter one of below in "Search Template:"
Single line
// $CommentContent$
Multi line
/*
$CommentContent$
*/
Javadoc
/**
$CommentContent$
*/
Leave the "Replacement Template:" blank
Select appropriate Scope
Click 'Find' and then 'Replace all'
you Should see no more comments
Note: that this might mess up formatting so you will have to reformat affected code
Press ctrl + r and in first textbox type //.*\n and then press replace all button. Then reformat the file by ctrl + alt + l.
The Comment Java Preprocessor allows to cut all commentaries from Java sources (the /R option)
http://code.google.com/p/java-comment-preprocessor/
Press control + r to open replace and replace all box
type //.* in first box, keep in second box empty and then select Regex. Select replace or replace all
That's it.
Enjoy 😎
My solution is:
find . -name *.java -type f -exec sh -c "perl -0pe 's#/\*(.|\n)*?\*/##g; s|//.*?\n|\n|g' '{}' > temp.java; cat temp.java > {} ; rm temp.java;" \;