Remove source file comments using IntelliJ? - java

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;" \;

Related

Vim: BufNewFile autocmd does not work when inside filetype plugin

Background story: I want vim to generate a public class declaration when editing new java files, so I wrote the following augroup:
augroup generate_public_class_declaration_upon_creation
au!
autocmd BufNewFile *.java execute "normal! ipublic class " . expand('%:t:r') . "\<CR>{}\<Left>\<CR>\<CR>\<Up>\<Tab>" | startinsert
augroup END
Which works fine when put in .vimrc, but no longer functions after being transferred to ftplugin/java.vim. I tried some other events e.g. BufWritePre, BufWinEnter inside java.vim and nothing goes wrong. What's happening?
By the time that snippet is executed from your ftplugin it is already too late for catching the BufNewFile event.
You can either leave it in your vimrc, where it is known to work, or modify it so that it can be executed from your ftplugin.
Here is a quick and dirty solution:
" in after/ftplugin/java.vim
if !(bufname()->filereadable())
execute "normal! ipublic class " . expand('%:t:r') . "\<CR>{}\<Left>\<CR>\<CR>\<Up>\<Tab>" | startinsert!
endif
where we check if there is a file for the current buffer before inserting our skeleton.
Basically, when you do :e foo.java or $ vim foo.java, a buffer is created with the name foo.java, which is supposed to be the name of the associated file and can be retrieved with :help bufname(). If a file with that name doesn't exist, we check with :help filereadable(), we can insert the skeleton.
Note the ! after startinsert: without it the insertion would happen before the <Tab>. See :help :startinsert.

change a line using 'sed" command for Java/Android

I am trying to change a line using 'sed" command for Android. I have used the following commands but it is not working. Noted here, my file location is in "root" folder at Android device. I also want to change the value from 20 to 10.
String[] cmd = { "su", "#!/bin/bash\n",
"sed -i 's/p2p_oper_channel/replacing_text/g' data/misc/wifi/p2p_supplicant.conf" };
Process p = Runtime.getRuntime().exec(cmd);
Can anone help me about this issue?
Using the sed command like that will only execute the substitution but it will output to stdout. You probably want to apply the substitution to the original file. To achieve that you need to supply an option to sed, the -i option for inline change.
Your command should therefor look like this:
sed -i 's/pattern_text=20/text_to_replace=10/g' /data/location/to/file.txt
Edit
In light if your most recent details, here's a command that ought to work:
sed -i 's/\(p2p_oper_channel=\)[0-9]\+/\1x/' /data/misc/wifi/p2p_supplicant.conf
Note that the part \1 means insert the part between the \( and \), i.e. the string p2p_oper_channel and the x will insert an x. Change the x to the number you want to insert instead of the current one.
This is the most flexible way, now let's take the most static one.
sed -i 's/p2p_oper_channel=[0-9]\+/p2p_oper_channel=x/' /data/misc/wifi/p2p_supplicant.conf
Where you, again, replace x with the desired value.
Edit2
Thanks to Wintermute's input, we found out escape symbols need to be escaped in Java. Reuslting in a new sed function:
sed -i 's/p2p_oper_channel=[0-9]\\+/p2p_oper_channel=x/' /data/misc/wifi/p2p_supplicant.conf

Matlab: How to use javaaddpath dynamically

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.

Syntax error on token "Invalid Character", delete this token

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

How do I make vim indent java annotations correctly?

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

Categories

Resources