aligning or prettifying code in emacs - emacs

I remember this was possible in emacs, but don't know how. If I have something like:
'abc' => 1,
'abcabc' =>2,
'abcabcabc' => 3,
How can I align the keys, arrows and values to something like this?
'abc' => 1,
'abcabc' => 2,
'abcabcabc' => 3,
Cheers

Select the region.
Type M-x align-regexp RET
Type = and hit enter.

You can also use the align command instead of align-regexp. The difference is that align automatically chooses the regular expression(s) to use based on the major-mode of the buffer. So if you are trying to align a block of variable initializations and assignments in a c-mode file, then it will automatically do the right thing without you needing to think of the regular expressions which are needed. Can be convenient.
For example select the following lines:
int x = 3;
double y = 9.0;
unsigned int z = 6;
const char c = 'A';
And type M-x align RET. The result is:
int x = 3;
double y = 9.0;
unsigned int z = 6;
const char c = 'A';
I should add, though, that this will not always work. If there are no regular expressions defined for the major-mode of the current buffer, then the call to align will do nothing. Then, you need to fall back on align-regexp. But this is hardly a large inconvenience. I actually use align-regexp fairly frequently. For convenience, I have defined an alias to save myself a few key-strokes:
(defalias 'ar #'align-regexp)

Related

Why are macros based on abstract syntax trees better than macros based on string preprocessing?

I am beginning my journey of learning Rust. I came across this line in Rust by Example:
However, unlike macros in C and other languages, Rust macros are expanded into abstract syntax trees, rather than string preprocessing, so you don't get unexpected precedence bugs.
Why is an abstract syntax tree better than string preprocessing?
If you have this in C:
#define X(A,B) A+B
int r = X(1,2) * 3;
The value of r will be 7, because the preprocessor expands it to 1+2 * 3, which is 1+(2*3).
In Rust, you would have:
macro_rules! X { ($a:expr,$b:expr) => { $a+$b } }
let r = X!(1,2) * 3;
This will evaluate to 9, because the compiler will interpret the expansion as (1+2)*3. This is because the compiler knows that the result of the macro is supposed to be a complete, self-contained expression.
That said, the C macro could also be defined like so:
#define X(A,B) ((A)+(B))
This would avoid any non-obvious evaluation problems, including the arguments themselves being reinterpreted due to context. However, when you're using a macro, you can never be sure whether or not the macro has correctly accounted for every possible way it could be used, so it's hard to tell what any given macro expansion will do.
By using AST nodes instead of text, Rust ensures this ambiguity can't happen.
A classic example using the C preprocessor is
#define MUL(a, b) a * b
// ...
int res = MUL(x + y, 5);
The use of the macro will expand to
int res = x + y * 5;
which is very far from the expected
int res = (x + y) * 5;
This happens because the C preprocessor really just does simple text-based substitutions, it's not really an integral part of the language itself. Preprocessing and parsing are two separate steps.
If the preprocessor instead parsed the macro like the rest of the compiler, which happens for languages where macros are part of the actual language syntax, this is no longer a problem as things like precedence (as mentioned) and associativity are taken into account.

Ncurses no-wrap mode when adding strings to window

I'm adding strings to a window, with waddwstr() function, one line after other, in consecutive rows. I don't want ncurses to automatically wrap lines for me – I'm overwriting them with consecutive calls to waddwstr() and sometimes tail of previous line is left displaying. Can ncurses just stop when right edge of window is reached?
The non-wrapping functions have "ch" in their name, e.g., wadd_wchstr.
The same is true of the non-wide interfaces waddstr versus waddchstr.
However, the wrapping/non-wrapping functions differ by more than that. They use different parameter types. The wrapping functions rely upon the video attributes set via wattr_set, etc., while the non-wrapping functions combine the video-attributes with the character data:
waddstr and waddchstr use char* and chtype* parameters, respectively
waddwstr and wadd_chstr use wchar_t* and cchar_t* parameters.
Converting between the two forms can be a nuisance, because X/Open, etc., did not define functions for doing the conversion.
The manual page for bkgd describes how these video attributes are combined with the background character to obtain the actual display.
The accepted answer (by Mr. Dickey) is correct. However, the "ch" functions do not work with ordinary C strings (array of bytes). Another solution is to create a wrapper for waddstr which checks the current cursor position and window size and prints only as much as would fit.
For example:
int waddstr_trunc(WINDOW *win, const char *str)
{
int cur_x, max_x, dummy [[maybe_unused]];
getyx(win, dummy, cur_x);
getmaxyx(win, dummy, max_x);
int w=max_x - cur_x;
if (w <= 0) return 0;
char *str2 = strndup(str, w);
if (str2 == NULL) return 1;
int rv = waddstr(win, str2);
free(str2);
return rv;
}

use macro to extract several object fields in Julia

I have a structure, from which I want to access repeatedly the fields to I load them in the current space like this (where M is type with fields X and Y):
X = M.X
Y = M.Y
in R, I often use the with command to do that. For now I would just like to be able to have a macro that expends that code, something along the lines of
#attach(M,[:X,:Y])
I am just not sure how exactly to do this.
I've included in this answer a macro that does pretty much what you describe. Comments explaining what's going on are inline.
macro attach(struct, fields...)
# we want to build up a block of expressions.
block = Expr(:block)
for f in fields
# each expression in the block consists of
# the fieldname = struct.fieldname
e = :($f = $struct.$f)
# add this new expression to our block
push!(block.args, e)
end
# now escape the evaled block so that the
# new variable declarations get declared in the surrounding scope.
return esc(:($block))
end
You use it like this: #attach M, X, Y
you can see the generated code like so: macroexpand(:(#attach M, X, Y)) which will show something like this:
quote
X = M.X
Y = M.Y
end

How to correctly format function calls in emacs

Does anybody know how to remove unwanted whitespace between function parameters.
for example I have a badly formatted function
foo ( int a , int b );
and I would like to get
foo (int a, int b);
I am looking for somethink similar to clean-ups or colon and brace hanging in CC mode. Ideally the correction is done when typing or pressing tab.
Thanks!
Using query-replace-regexp:
M-C-S 5( +Enter(Enter!
M-C-S 5+,Enter,Enter!
M-C-S 5+)Enter)Enter!

Does MATLAB lets you assign default value for input arguments for a function like python does?

I am working on a project and have many functions to create and they do need lots of debugging so instead of just hitting the run button i have to go to command window and give a function call.
does MATLAB support assignment of default values to input arguments like python does?
In python
def some_fcn(arg1 = a, arg2 = b)
% THE CODE
if you now call it without passing the arguments it doesn't give errors but if you try the same in MATLAB it gives an error.
For assigning default values, one might find it easier to manage if you use exist function instead of nargin.
function f(arg1, arg2, arg3)
if ~exist('arg2', 'var')
arg2 = arg2Default;
end
The advantage is that if you change the order of arguments, you don't need to update this part of the code, but when you use nargin you have to start counting and updating numbers.
If you are writing a complex function that requires validation of inputs, default argument values, key-value pairs, passing options as structs etc., you could use the inputParser object. This solution is probably overkill for simple functions, but you might keep it in mind for your monster-function that solves equations, plots results and brings you coffee. It resembles a bit the things you can do with python's argparse module.
You configure an inputParser like so:
>> p = inputParser();
>> p.addRequired('x', #isfinite) % validation function
>> p.addOptional('y', 123) % default value
>> p.addParamValue('label', 'default') % default value
Inside a function, you would typically call it with p.parse(varargin{:}) and look for your parameters in p.Results. Some quick demonstration on the command line:
>> p.parse(44); disp(p.Results)
label: 'default'
x: 44
y: 123
>> p.parse()
Not enough input arguments.
>> p.parse(Inf)
Argument 'x' failed validation isfinite.
>> p.parse(44, 55); disp(p.Results)
label: 'default'
x: 44
y: 55
>> p.parse(13, 'label', 'hello'); disp(p.Results)
label: 'hello'
x: 13
y: 123
>> p.parse(88, 13, 'option', 12)
Argument 'option' did not match any valid parameter of the parser.
You can kind of do this with nargin
function out = some_fcn(arg1, arg2)
switch nargin
case 0
arg1 = a;
arg2 = b;
%//etc
end
but where are a and b coming from? Are they dynamically assigned? Because that effects the validity of this solution
After a few seconds of googling I found that as is often the case, Loren Shure has already solved this problem for us. In this article she outlines exactly my method above, why it is ugly and bad and how to do better.
You can use nargin in your function code to detect when no arguments are passed, and assign default values or do whatever you want in that case.
MathWorks has a new solution for this in R2019b, namely, the arguments block. There are a few rules for the arguments block, naturally, so I would encourage you to learn more by viewing the Function Argument Validation help page. Here is a quick example:
function ret = someFunction( x, y )
%SOMEFUNCTION Calculates some stuff.
arguments
x (1, :) double {mustBePositive}
y (2, 3) logical = true(2, 3)
end
% ...stuff is done, ret is defined, etc.
end
Wrapped into this is narginchk, inputParser, validateattributes, varargin, etc. It can be very convenient. Regarding default values, they are very simply defined as those arguments that equal something. In the example above, x isn't given an assignment, whereas y = true(2, 3) if no value is given when the function is called. If you wanted x to also have a default value, you could change it to, say, x (1, :) double {mustBePositive} = 0.5 * ones(1, 4).
There is a more in-depth answer at How to deal with name/value pairs of function arguments in MATLAB
that hopefully can spare you some headache in getting acquainted with the new functionality.